package main import ( "biukop.com/sfm/loan" "database/sql" "encoding/json" log "github.com/sirupsen/logrus" "net/http" "time" ) type loginForm struct { Login string `json:"u"` Pass string `json:"p"` } func apiV1Login(w http.ResponseWriter, r *http.Request, ss *loan.Session) { res := apiV1ResponseBlank() l := loginForm{} e := l.retrieveLoginForm(r) if e != nil { log.Warn("Failed login - cannot analyze request " + e.Error()) res.add("login", false) res.add("reason", "incomplete request") res.sendJson(w) return } //try login _, e = ss.Login(l.Login, l.Pass) if e == sql.ErrNoRows { //not found log.Warnf("Failed login - user not found %+v, error=%s", l, e.Error()) res.add("login", false) res.add("reason", "User not found") res.sendJson(w) return } else if e != nil { log.Warn("Failed login - cannot init session " + e.Error()) res.add("login", false) res.add("reason", "either user name or password is not right") res.sendJson(w) return } else { //Audit user login, in db log.Info("login success ", l.Login) } //format response res.add("login", true) res.add("role", ss.GetRole()) u, e := ss.GetUser() if e == nil { res.add("User", u.People) res.add("UserExtra", getUserExtraForLogin(u, ss)) } res.add("Biukop-Session", ss.Id) res.add("Biukop-Mid", ss.Get("Biukop-Mid")) res.add("sessionExpire", ss.ExpireStr()) res.add("sessionExpireHuman", ss.Expire.Format(time.RFC1123Z)) if config.Debug { u, e := ss.GetUser() if e == nil { res.Env.Body["debug_session_user"] = u res.Env.Session = *ss } else { log.Warn("cannot read user for session ", ss) res.Env.Body["debug_session_user_error"] = e.Error() } } WsNotifyNewLogin(ss) //send out apiV1AddTrackingCookie(w, r, ss) //always the last one to set cookies res.sendJson(w) } func getUserExtraForLogin(u loan.User, ss *loan.Session) (ret UserExtra) { if ss.GetRole() == "user" { ret = UserExtra{ Login: u.Login, BSB: "", ACC: "", License: "", Organization: "", Role: "user", } } if ss.GetRole() == "broker" { broker := loan.Broker{} e := broker.Read(ss.User) if e != nil { log.Error("fail to retrieve broker for session ", ss, e.Error()) } else { ret = UserExtra{ Login: broker.Login, BSB: broker.BSB, ACC: broker.ACC, License: broker.License, Organization: broker.Organization, Role: "broker", } } } if ss.GetRole() == "admin" { ret = UserExtra{ Login: u.Login, BSB: "", ACC: "", License: "", Organization: "SFM", Role: "admin", } } return } func (m *loginForm) retrieveLoginForm(r *http.Request) (e error) { e = apiV1DecodeRequestBody(m, r) if e != nil { log.Error(e) return } return } func apiV1DecodeRequestBody(bb interface{}, r *http.Request) (e error) { decoder := json.NewDecoder(r.Body) decoder.DisallowUnknownFields() e = decoder.Decode(bb) return }