/
auth.go
57 lines (44 loc) · 1.29 KB
/
auth.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
package repo
import (
"context"
"errors"
"log"
"github.com/ilmsg/studious-barnacle/auth-grpc/model"
"github.com/ilmsg/studious-barnacle/auth-grpc/utils"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
type RepoAuth struct {
collection *mongo.Collection
}
var (
errInvalidPassword = errors.New("invalid password")
errCreateToken = errors.New("something wrong on create jwt token")
errExistsEmail = errors.New("exists email")
)
func NewRepoAuth(collection *mongo.Collection) *RepoAuth {
return &RepoAuth{collection}
}
func (r *RepoAuth) Register(email, password string) (string, error) {
var authLogin model.AuthLogin
filter := bson.D{{"email", email}}
if err := r.collection.FindOne(context.Background(), filter).Decode(&authLogin); err != nil {
return "", errExistsEmail
}
return "", nil
}
func (r *RepoAuth) Login(email, password string) (string, error) {
var authLogin model.AuthLogin
filter := bson.D{{"email", email}}
if err := r.collection.FindOne(context.Background(), filter).Decode(&authLogin); err != nil {
log.Fatal(err)
}
if !utils.CheckPasswordHash(password, authLogin.Password) {
return "", errInvalidPassword
}
token, err := utils.CreateToken(authLogin.Id)
if err != nil {
return "", errCreateToken
}
return token, nil
}