github.com/apremalal/vamps-core@v1.0.1-0.20161221121535-d430b56ec174/api/authentication_handler.go (about) 1 package api 2 3 import ( 4 "encoding/json" 5 "net/http" 6 "strings" 7 8 "github.com/vedicsoft/vamps-core/commons" 9 "github.com/vedicsoft/vamps-core/controllers" 10 "github.com/vedicsoft/vamps-core/models" 11 ) 12 13 func Login(w http.ResponseWriter, r *http.Request) *commons.AppError { 14 requestUser := new(models.SystemUser) 15 decoder := json.NewDecoder(r.Body) 16 err := decoder.Decode(&requestUser) 17 if err != nil { 18 return &commons.AppError{err, "Unable to decode the json request body", 500} 19 } 20 results := strings.Split(requestUser.Username, "@") 21 if len(results) > 1 { 22 requestUser.Username = results[0] 23 requestUser.TenantDomain = results[1] 24 } else { 25 //setting default 26 requestUser.TenantDomain = "super.com" 27 } 28 responseStatus, token, err := controllers.Login(requestUser) 29 if err != nil { 30 return &commons.AppError{err, "error while authenticating user", 500} 31 } else { 32 w.Header().Set("Content-Type", "application/json") 33 w.WriteHeader(responseStatus) 34 w.Write(token) 35 } 36 return nil 37 } 38 39 func RefreshToken(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) *commons.AppError { 40 requestUser := new(models.SystemUser) 41 decoder := json.NewDecoder(r.Body) 42 err := decoder.Decode(&requestUser) 43 if err != nil { 44 return &commons.AppError{err, "Unable to decode the json request body", 500} 45 } 46 w.Header().Set("Content-Type", "application/json") 47 w.Write(controllers.RefreshToken(requestUser)) 48 return nil 49 } 50 51 func Logout(w http.ResponseWriter, r *http.Request) *commons.AppError { 52 err := controllers.Logout(r) 53 if err != nil { 54 return &commons.AppError{err, "Unable to logout", 500} 55 } else { 56 w.WriteHeader(http.StatusOK) 57 } 58 return nil 59 }