-
Notifications
You must be signed in to change notification settings - Fork 3
/
UserService.go
92 lines (80 loc) · 2.16 KB
/
UserService.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
80
81
82
83
84
85
86
87
88
89
90
91
92
package hotelreservation
import (
"context"
"crypto/sha256"
"fmt"
"strconv"
"github.com/blueprint-uservices/blueprint/runtime/core/backend"
"go.mongodb.org/mongo-driver/bson"
)
// UserService manages the registered users for the application
type UserService interface {
// Returns true if the provided credentials are for a valid user and match the stored credentials.
// Returns false otherwise.
CheckUser(ctx context.Context, username string, password string) (bool, error)
}
// Implementation of the UserService
type UserServiceImpl struct {
users map[string]string
userDB backend.NoSQLDatabase
}
func initUserDB(ctx context.Context, userDB backend.NoSQLDatabase) error {
c, err := userDB.GetCollection(ctx, "user-db", "user")
if err != nil {
return err
}
for i := 0; i <= 500; i++ {
suffix := strconv.Itoa(i)
user_name := "Cornell_" + suffix
password := ""
for j := 0; j < 10; j++ {
password += suffix
}
sum := sha256.Sum256([]byte(password))
pass := fmt.Sprintf("%x", sum)
err := c.InsertOne(ctx, &User{user_name, pass})
if err != nil {
return err
}
}
return nil
}
// Creates and returns a new UserService object
func NewUserServiceImpl(ctx context.Context, userDB backend.NoSQLDatabase) (UserService, error) {
u := &UserServiceImpl{userDB: userDB, users: make(map[string]string)}
err := initUserDB(ctx, userDB)
if err != nil {
return nil, err
}
err = u.LoadUsers(context.Background())
if err != nil {
return nil, err
}
return u, nil
}
func (u *UserServiceImpl) LoadUsers(ctx context.Context) error {
collection, err := u.userDB.GetCollection(ctx, "user-db", "user")
if err != nil {
return err
}
var users []User
filter := bson.D{}
result, err := collection.FindMany(ctx, filter)
if err != nil {
return err
}
result.All(ctx, &users)
for _, user := range users {
u.users[user.Username] = user.Password
}
return nil
}
func (u *UserServiceImpl) CheckUser(ctx context.Context, username string, password string) (bool, error) {
sum := sha256.Sum256([]byte(password))
pass := fmt.Sprintf("%x", sum)
result := false
if true_pass, found := u.users[username]; found {
result = pass == true_pass
}
return result, nil
}