forked from tanitall/memo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
login.go
48 lines (39 loc) · 1.15 KB
/
login.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
package auth
import (
"github.com/memocash/memo/app/db"
"github.com/jchavannes/jgo/jerr"
"golang.org/x/crypto/bcrypt"
"strings"
)
const (
MsgUsernameNotFound = "username not found"
MsgPasswordMismatch = "password hash mismatch"
)
func IsBadUsernamePasswordError(err error) bool {
return jerr.HasError(err, MsgUsernameNotFound) || jerr.HasError(err, MsgPasswordMismatch)
}
// Reasonable assumption here but error creating user might not mean already exists in edge cases.
func UserAlreadyExists(err error) bool {
return jerr.HasError(err, MsgErrorCreatingUser)
}
func Login(cookieId string, username string, password string) error {
username = strings.ToLower(username)
user, err := db.GetUserByUsername(username)
if err != nil {
return jerr.Get(MsgUsernameNotFound, err)
}
err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password))
if err != nil {
return jerr.Get(MsgPasswordMismatch, err)
}
session, err := db.GetSession(cookieId)
if err != nil {
return jerr.Get("session not found", err)
}
session.UserId = user.Id
err = session.Save()
if err != nil {
return jerr.Get("session save failed", err)
}
return nil
}