You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
110 lines
2.1 KiB
Go
110 lines
2.1 KiB
Go
package auth
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"git.phc.dm.unipi.it/phc/website/model"
|
|
"git.phc.dm.unipi.it/phc/website/util"
|
|
)
|
|
|
|
var exampleMemoryUsers = &Memory{
|
|
Users: map[string]*memoryUser{
|
|
"aziis98": {
|
|
User: model.User{
|
|
Username: "aziis98",
|
|
Name: "Antonio",
|
|
Surname: "De Lucreziis",
|
|
Email: "aziis98@example.org",
|
|
}.WithDefaultFullName(),
|
|
Password: "123",
|
|
},
|
|
"bachoseven": {
|
|
User: model.User{
|
|
Username: "bachoseven",
|
|
Name: "Francesco",
|
|
Surname: "Minnocci",
|
|
Email: "bachoseven@example.org",
|
|
}.WithDefaultFullName(),
|
|
Password: "234",
|
|
},
|
|
},
|
|
Sessions: map[string]*memorySession{},
|
|
}
|
|
|
|
type memoryUser struct {
|
|
model.User
|
|
Password string `json:"-"`
|
|
}
|
|
|
|
func (u memoryUser) AsUser() *model.User {
|
|
return &model.User{
|
|
Username: u.Username,
|
|
Name: u.Name,
|
|
Surname: u.Surname,
|
|
FullName: u.FullName,
|
|
Email: u.Email,
|
|
}
|
|
}
|
|
|
|
type memorySession struct {
|
|
Username string
|
|
Token string
|
|
}
|
|
|
|
func (s memorySession) AsSession() *model.Session {
|
|
return &model.Session{
|
|
Username: s.Username,
|
|
Token: s.Token,
|
|
}
|
|
}
|
|
|
|
type Memory struct {
|
|
Users map[string]*memoryUser
|
|
Sessions map[string]*memorySession
|
|
}
|
|
|
|
func (m *Memory) GetUser(username string) (*model.User, error) {
|
|
user, ok := m.Users[username]
|
|
if !ok {
|
|
return nil, fmt.Errorf(`no user with that username`)
|
|
}
|
|
|
|
return user.AsUser(), nil
|
|
}
|
|
|
|
func (m *Memory) GetUsers() ([]*model.User, error) {
|
|
users := make([]*model.User, len(m.Users))
|
|
i := 0
|
|
for _, u := range m.Users {
|
|
users[i] = u.AsUser()
|
|
i++
|
|
}
|
|
|
|
return users, nil
|
|
}
|
|
|
|
func (m *Memory) GetSession(token string) (*model.Session, error) {
|
|
session, ok := m.Sessions[token]
|
|
if !ok {
|
|
return nil, ErrInvalidSession
|
|
}
|
|
|
|
return session.AsSession(), nil
|
|
}
|
|
|
|
func (m *Memory) Login(username string, password string) (*model.Session, error) {
|
|
user, ok := m.Users[username]
|
|
if !ok {
|
|
return nil, fmt.Errorf(`no user with that username`)
|
|
}
|
|
|
|
if user.Password != password {
|
|
return nil, fmt.Errorf(`invalid credentials`)
|
|
}
|
|
|
|
session := &memorySession{username, util.GenerateRandomString(15)}
|
|
m.Sessions[session.Token] = session
|
|
|
|
return session.AsSession(), nil
|
|
}
|