package api import ( "fmt" "regexp" "github.com/gin-gonic/gin" "immae.eu/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front/db" ) const ( VALID_EMAIL_REGEX = `(?i)^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$` ) func IsValidEmailAddress(email string) bool { r := regexp.MustCompile(VALID_EMAIL_REGEX) return r.MatchString(email) } type SignParams struct { Email string Password string } type SignResult struct { Token string `json:"token"` } func (s SignParams) Validate() *Error { if !IsValidEmailAddress(s.Email) { return &Error{InvalidEmail, "invalid email", fmt.Errorf("'%v' is not a valid email", s.Email)} } if s.Password == "" { return &Error{InvalidPassword, "invalid password", fmt.Errorf("invalid password")} } return nil } type SignupQuery struct { In SignParams } func (q SignupQuery) ValidateParams() *Error { return q.In.Validate() } func (q SignupQuery) Run() (interface{}, *Error) { user, err := db.GetUserByEmail(q.In.Email) if err != nil { return nil, NewInternalError(err) } if user != nil { return nil, &Error{EmailExists, "email already taken", fmt.Errorf("'%v' is already registered '%v'", q.In.Email, user)} } newUser := db.User{Email: q.In.Email, Status: db.AwaitingConfirmation} newUser.PasswordHash, err = db.HashPassword(q.In.Password) if err != nil { return nil, NewInternalError(err) } err = db.InsertUser(&newUser) if err != nil { return nil, NewInternalError(err) } token, err := CreateJwtToken(newUser.Id) if err != nil { return nil, NewInternalError(fmt.Errorf("cannot create jwt token %v", err)) } if CONFIG.FreeSMSUser != "" { err := SendSMS(CONFIG.FreeSMSUser, CONFIG.FreeSMSPass, fmt.Sprintf("New user signup '%v'", q.In.Email)) if err != nil { return nil, NewInternalError(err) } } return SignResult{token}, nil } type SigninQuery struct { In SignParams } func (q SigninQuery) ValidateParams() *Error { return q.In.Validate() } func (q SigninQuery) Run() (interface{}, *Error) { user, err := db.GetUserByEmail(q.In.Email) if err != nil { return nil, NewInternalError(err) } if user == nil { return nil, &Error{InvalidCredentials, "invalid credentials", fmt.Errorf("no email '%v' found", q.In.Email)} } err = db.ValidatePassword(q.In.Password, user.PasswordHash) if err != nil { return nil, &Error{InvalidCredentials, "invalid credentials", err} } token, err := CreateJwtToken(user.Id) if err != nil { return nil, NewInternalError(err) } return SignResult{token}, nil } func UserConfirmed(c *gin.Context) *Error { user, exists := c.Get("user") if !exists { return &Error{NotAuthorized, "not authorized", fmt.Errorf("no user key in context")} } if user.(db.User).Status != db.Confirmed { return &Error{UserNotConfirmed, "user awaiting admin validation", fmt.Errorf("user '%v' not confirmed", user)} } return nil } func GetUser(c *gin.Context) db.User { user, _ := c.Get("user") return user.(db.User) }