go-sample-webpage/pkg/user/userclient.go

70 lines
1.5 KiB
Go
Raw Normal View History

2021-11-04 02:04:05 +00:00
package user
import (
"errors"
"fmt"
2021-11-22 22:11:37 +00:00
"math/rand"
2021-11-04 02:04:05 +00:00
)
type UserClient interface {
2021-11-09 18:23:19 +00:00
register(username, password, email string) (bool, error)
2021-11-22 22:11:37 +00:00
login(username, password string, requiredMailValidation bool) (bool, error)
getMailValidationToken(forceRecreate bool) (string, error)
2021-11-04 02:04:05 +00:00
}
type UserClientMemory struct {
users map[string]string
}
var u *UserClientMemory
2021-11-22 22:46:01 +00:00
func GetUserMemmoryClient() *UserClientMemory {
2021-11-04 02:04:05 +00:00
if u == nil {
uc := UserClientMemory{}
uc.users = make(map[string]string)
uc.users["admin"]="password"
u = &uc
}
return u
}
2021-11-09 18:23:19 +00:00
func (uc *UserClientMemory) register(username, password, email string) (bool, error) {
2021-11-04 02:04:05 +00:00
if _, ok := uc.users[username]; ok {
return false, errors.New("Username already used")
}
uc.users[username] = password
return true, nil
}
2021-11-22 22:11:37 +00:00
func (uc UserClientMemory) login(username, password string, requiredMailValidation bool) (bool, error) {
if requiredMailValidation == true {
return false, errors.New("In memmory User Client cant validate email addresses")
}
2021-11-04 02:04:05 +00:00
if val, ok := uc.users[username]; ok {
fmt.Println("Login for valide user")
if val == password {
return true, nil
}
} else {
fmt.Printf("User %v not found", username)
}
return false, nil
2021-11-22 22:11:37 +00:00
}
func (uc UserClientMemory) getMailValidationToken(forceRecreate bool) (string, error) {
token := randomString(5)
return token, nil
}
func randomString(n int) string {
var letters = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
b := make([]byte, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
2021-11-04 02:04:05 +00:00
}