forked from ortuman/jackal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth_plain.go
79 lines (66 loc) · 1.57 KB
/
auth_plain.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
* Copyright (c) 2018 Miguel Ángel Ortuño.
* See the LICENSE file for more information.
*/
package server
import (
"bytes"
"encoding/base64"
"github.com/ortuman/jackal/storage"
"github.com/ortuman/jackal/stream/c2s"
"github.com/ortuman/jackal/xml"
)
type plainAuthenticator struct {
strm c2s.Stream
username string
authenticated bool
}
func newPlainAuthenticator(strm c2s.Stream) *plainAuthenticator {
return &plainAuthenticator{strm: strm}
}
func (p *plainAuthenticator) Mechanism() string {
return "PLAIN"
}
func (p *plainAuthenticator) Username() string {
return p.username
}
func (p *plainAuthenticator) Authenticated() bool {
return p.authenticated
}
func (p *plainAuthenticator) UsesChannelBinding() bool {
return false
}
func (p *plainAuthenticator) ProcessElement(elem xml.XElement) error {
if p.authenticated {
return nil
}
if len(elem.Text()) == 0 {
return errSASLMalformedRequest
}
b, err := base64.StdEncoding.DecodeString(elem.Text())
if err != nil {
return errSASLIncorrectEncoding
}
s := bytes.Split(b, []byte{0})
if len(s) != 3 {
return errSASLIncorrectEncoding
}
username := string(s[1])
password := string(s[2])
// validate user and password
user, err := storage.Instance().FetchUser(username)
if err != nil {
return err
}
if user == nil || user.Password != password {
return errSASLNotAuthorized
}
p.username = username
p.authenticated = true
p.strm.SendElement(xml.NewElementNamespace("success", saslNamespace))
return nil
}
func (p *plainAuthenticator) Reset() {
p.username = ""
p.authenticated = false
}