Ejemplo n.º 1
0
// RefreshTokenHandler handles POST /users/refreshToken
func RefreshTokenHandler(w http.ResponseWriter, r *http.Request) {
	decoder := json.NewDecoder(r.Body)
	var b refreshTokenBody
	err := decoder.Decode(&b)

	if err != nil {
		http.Error(w, "Invalid Body.", http.StatusBadRequest)
		return
	}

	user, err := auth.ValidateJWTToken(b.Token)

	if err != nil {
		http.Error(w, err.Error(), http.StatusForbidden)
		return
	}

	token, err := auth.GenerateJWTToken(*user)

	if err != nil {
		http.Error(w, err.Error(), http.StatusForbidden)
		return
	}

	err = auth.InvalidateToken(b.Token)

	if err != nil {
		InternalServerError(err, w)
		return
	}

	user.AvatarURL = os.Getenv("BASE_URL") + "/users/" + user.Name + "/avatar"

	bytes, err := json.Marshal(authResponseBody{Token: token, User: *user})

	if err != nil {
		InternalServerError(err, w)
		return
	}

	w.Write(bytes)
}
Ejemplo n.º 2
0
// AuthHandler handles POST /users/auth
func AuthHandler(w http.ResponseWriter, r *http.Request) {
	decoder := json.NewDecoder(r.Body)
	var b authBody
	err := decoder.Decode(&b)

	if err != nil {
		http.Error(w, "Invalid Body.", http.StatusBadRequest)
		return
	}

	googleID, err := firebase.VerifyIDToken(b.GoogleToken, os.Getenv("FIREBASE_PROJECT_ID"))

	if err != nil {
		http.Error(w, err.Error(), http.StatusForbidden)
		return
	}

	user, err := models.FindUserByGoogleIDOrInit(googleID)

	if err != nil {
		InternalServerError(err, w)
		return
	}

	if user.Name == "" {
		id := hash(googleID)

		name := ""
		i := 0
		for name == "" {
			genName, err2 := nameGen.GenerateNameWithSeed(1, 1, 3, int64(id+uint32(i)))
			if err2 != nil {
				http.Error(w, err2.Error(), http.StatusForbidden)
				return
			}

			count, err3 := models.CountUsersByName(genName)
			if err3 != nil {
				InternalServerError(err, w)
				return
			}

			if count == 0 {
				name = genName
			}
			i = i + 1
		}

		user.Name = name
		user.Balance = scores.InitialBalance
	}

	err = user.Save()
	if err != nil {
		InternalServerError(err, w)
		return
	}

	token, err := auth.GenerateJWTToken(user)

	if err != nil {
		http.Error(w, err.Error(), http.StatusForbidden)
		return
	}

	user.AvatarURL = os.Getenv("BASE_URL") + "/users/" + user.Name + "/avatar"

	bytes, err := json.Marshal(authResponseBody{Token: token, User: user})

	if err != nil {
		InternalServerError(err, w)
		return
	}

	w.Write(bytes)
}