Exemple #1
0
// UpdateUser Updates user by user id.
func UpdateUser(w rest.ResponseWriter, r *rest.Request) {
	var err error

	u, err := user.New()
	if err != nil {
		log.Printf("UpdateUser: User update failed: %s", err)
		rest.Error(w, "User update failed", 500)
		return
	}

	decoder := json.NewDecoder(r.Body)
	err = decoder.Decode(&u)
	if err != nil {
		log.Printf("UpdateUser: Failed to decode request body: %s", err)
		rest.Error(w, "Failed to decode request body", 500)
		return
	}

	if u.Uid == "" {
		log.Println("UpdateUser: Missing user id")
		rest.Error(w, "Missing user id", 422)
		return
	}

	if err := user.GetHandler().SaveUser(*u); err != nil {
		log.Printf("UpdateUser: Failed to update user: %s", err)
		rest.Error(w, "User update failed", 500)
		return
	}

	log.Printf("UpdateUser: User update was successful (%s)", u.Uid)
}
Exemple #2
0
// GetToken generates a user token.
func GetToken(w rest.ResponseWriter, r *rest.Request) {
	var u *user.User
	var tokenInfo *auth.Token
	var err error

	log.Println("GetToken")
	params := &auth.TokenRequest{}
	decoder := json.NewDecoder(r.Body)
	err = decoder.Decode(&params)
	if err != nil {
		log.Printf("GetToken: Failed to decode request body: %s", err)
		rest.Error(w, "Failed to decode request body", 500)
		return
	}

	conf, err := app.GetConfig("token-provider")
	log.Printf("GetToken: conf %s", conf)
	if err != nil {
		log.Printf("GetToken: Failed to load app configuration: %s", err)
		rest.Error(w, "Failed to generate user token", 500)
		return
	}

	// Load the configured token provider.
	provider := auth.NewTokenProvider(conf)
	tokenInfo, err = provider.GetTokenInfo(params.Token)
	log.Printf("GetToken: tokenInfo +%v", tokenInfo)
	if err != nil {
		log.Printf("GetToken: Token validation has failed: %s", err)
		rest.Error(w, "Invalid token", 400)
		return
	}

	u, err = user.GetHandler().RetrieveUserByMail(tokenInfo.Mail)
	log.Printf("GetToken: RetrieveUserByMail +%v", u)
	if err != nil {
		log.Printf("GetToken: Failed to load user: %s", err)
		rest.Error(w, "Failed to generate user token", 500)
		return
	}

	// If it's a new user, save it.
	if u == nil {
		u, err = user.New()
		if err != nil {
			log.Printf("GetToken: Failed to create user: %s", err)
			rest.Error(w, "Failed to generate user token", 500)
			return
		}

		u.Mail = tokenInfo.Mail
		err = user.GetHandler().SaveUser(*u)
		if err != nil {
			log.Printf("GetToken: Failed to create user: %s", err)
			rest.Error(w, "Failed to generate user token", 500)
			return
		}
	}

	// Create a token.
	token, err := auth.GenerateToken(*tokenInfo, *u)
	log.Printf("GetToken: GenerateToken %s", token)
	if err != nil {
		log.Printf("GetToken: Failed to generate token: %s", err)
		rest.Error(w, "Failed to generate user token", 500)
	}

	resp := auth.TokenResponse{User: u, Token: token}
	log.Printf("GetToken: +%v", resp)
	w.WriteJson(resp)
}