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.
115 lines
2.0 KiB
Go
115 lines
2.0 KiB
Go
package auth
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"git.phc.dm.unipi.it/phc/website/util"
|
|
)
|
|
|
|
var exampleMemoryUsers = &Memory{
|
|
Users: map[string]*MemoryUser{
|
|
"aziis98": {
|
|
Username: "aziis98",
|
|
Name: "Antonio",
|
|
Surname: "De Lucreziis",
|
|
Password: "123",
|
|
},
|
|
"bachoseven": {
|
|
Username: "bachoseven",
|
|
Name: "Francesco",
|
|
Surname: "Minnocci",
|
|
Password: "234",
|
|
},
|
|
},
|
|
Sessions: map[string]*MemorySession{},
|
|
}
|
|
|
|
type MemoryUser struct {
|
|
Username string `json:"username"`
|
|
Name string `json:"name"`
|
|
Surname string `json:"surname"`
|
|
|
|
Password string `json:"-"`
|
|
}
|
|
|
|
func (u *MemoryUser) GetUsername() string {
|
|
return u.Username
|
|
}
|
|
|
|
func (u *MemoryUser) GetName() string {
|
|
return u.Name
|
|
}
|
|
|
|
func (u *MemoryUser) GetSurname() string {
|
|
return u.Surname
|
|
}
|
|
|
|
func (u *MemoryUser) GetFullName() string {
|
|
return u.Name + " " + u.Surname
|
|
}
|
|
|
|
type MemorySession struct {
|
|
Username string
|
|
Token string
|
|
}
|
|
|
|
func (s *MemorySession) GetUsername() string {
|
|
return s.Username
|
|
}
|
|
|
|
func (s *MemorySession) GetToken() string {
|
|
return s.Token
|
|
}
|
|
|
|
type Memory struct {
|
|
Users map[string]*MemoryUser
|
|
Sessions map[string]*MemorySession
|
|
}
|
|
|
|
func (m *Memory) GetUser(username string) (User, error) {
|
|
user, ok := m.Users[username]
|
|
if !ok {
|
|
return nil, fmt.Errorf(`no user with that username`)
|
|
}
|
|
|
|
return user, nil
|
|
}
|
|
|
|
func (m *Memory) GetUsers() ([]User, error) {
|
|
users := make([]User, len(m.Users))
|
|
i := 0
|
|
for _, u := range m.Users {
|
|
users[i] = u
|
|
i++
|
|
}
|
|
|
|
return users, nil
|
|
}
|
|
|
|
func (m *Memory) GetSession(token string) (Session, error) {
|
|
session, ok := m.Sessions[token]
|
|
if !ok {
|
|
return nil, fmt.Errorf(`invalid session token`)
|
|
}
|
|
|
|
return session, nil
|
|
}
|
|
|
|
func (m *Memory) Login(username string, password string) (Session, error) {
|
|
user, err := m.GetUser(username)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
memUser := user.(*MemoryUser)
|
|
|
|
if memUser.Password != password {
|
|
return nil, fmt.Errorf(`invalid credentials`)
|
|
}
|
|
|
|
session := &MemorySession{username, util.GenerateRandomString(15)}
|
|
m.Sessions[session.Token] = session
|
|
|
|
return session, nil
|
|
}
|