예제 #1
0
func (h *LoginHandler) Post(ctx rest.Context) (int, interface{}) {
	log.Infof("Handling login request %q")
	ar := AuthRequest{}
	ctx.Deserialize(&ar)
	status := 200
	// Check for a cookie already present.
	c := getSessionCookie(ctx)
	if c == nil {
		c = &http.Cookie{}
		c.Name = authCookieName
		c.Value = simpleUUID4()
		// TODO(jwall): Session expiration?
		sess, err := h.ss.StartSession(c.Value)
		if err != nil {
			panic("Can't create user session. Something is very wrong!!!" + err.Error())
		}
		sess.Values[usernameKey] = ar.Username
		err = h.ss.Save(sess)
		if err != nil {
			panic("Can't save user session. Something is very wrong!!!" + err.Error())
		}
	} else {
		sess, err := h.ss.Get(c.Value)
		if err != nil || sess == nil {
			panic("Error Getting session " + err.Error())
		}
		if ar.Username != sess.Values[usernameKey].(string) {
			// Status 409 Conflict.
			// There is a conflict with the current session username
			// and the requested login username.
			return 409, nil
		}
	}
	if ok, err := ctx.Auth.Authenticate(ar.Username, ar.Password); ok {
		ctx.Header().Add("Set-Cookie", c.String())
	} else {
		log.Errorf("Unable to authenticate %q err %q", ar.Username, err)
		status = 403
	}
	return status, nil
}