package auth import ( "fmt" "git.phc.dm.unipi.it/phc/website/util" ) var exampleMemoryUsers = &Memory{ Users: map[string]*memoryUser{ "aziis98": { User: User{ Username: "aziis98", Name: "Antonio", Surname: "De Lucreziis", Email: "aziis98@example.org", }.WithDefaultFullName(), Password: "123", }, "bachoseven": { User: User{ Username: "bachoseven", Name: "Francesco", Surname: "Minnocci", Email: "bachoseven@example.org", }.WithDefaultFullName(), Password: "234", }, }, Sessions: map[string]*memorySession{}, } type memoryUser struct { User Password string `json:"-"` } func (u memoryUser) AsUser() *User { return &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() *Session { return &Session{ Username: s.Username, Token: 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.AsUser(), nil } func (m *Memory) GetUsers() ([]*User, error) { users := make([]*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) (*Session, error) { session, ok := m.Sessions[token] if !ok { return nil, ErrInvalidSession } return session.AsSession(), nil } func (m *Memory) Login(username string, password string) (*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 }