Esempio n. 1
0
func Authenticate(f func(http.ResponseWriter, *http.Request, *model.User) error) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var (
			user *model.User
			err  error
		)

		c, err := cookie.Read(r, "user")
		if err != nil {
			serveUnauthorized(w)
			return
		}

		userId := c.Values["id"]
		if userId == "" {
			serveUnauthorized(w)
			return
		}

		user = repository.User().FirstByObjectId(userId)
		if user == nil {
			serveUnauthorized(w)
			return
		}

		err = f(w, r, user)

		if err != nil {
			serveError(w, err)
			log.Printf("handling %q: %v", r.RequestURI, err)
		}
	}
}
Esempio n. 2
0
func LoginCallback(w http.ResponseWriter, r *http.Request) error {
	q := r.URL.Query()
	// TODO: verify state is the same
	state := q.Get("state")
	if state == "" {
		return fmt.Errorf("State can't be blank")
	}
	code := q.Get("code")
	if code == "" {
		return fmt.Errorf("Code can't be blank")
	}

	redirectURI := loginRedirectURI(r)
	accessToken, err := repository.GitHub("").CreateAccessToken(gitHubClientId, gitHubClientSecret, code, redirectURI)
	if err != nil {
		return err
	}

	githubUser, err := repository.GitHub(accessToken.Token).AuthenticatedUser()
	if err != nil {
		return err
	}

	userRepo := repository.User()
	user := &model.User{
		ID:          githubUser.ID,
		Login:       githubUser.Login,
		Email:       githubUser.Email,
		HTMLURL:     githubUser.HTMLURL,
		AvatarURL:   githubUser.AvatarURL,
		AccessToken: accessToken.Token,
		CreatedAt:   githubUser.CreatedAt,
	}
	user, err = userRepo.Upsert(user)
	if err != nil {
		return err
	}

	c := cookie.Cookie{Name: "user", Path: "/", Values: cookie.CookieValues{"id": user.ObjectIdString()}}
	cookie.Write(w, &c)

	redirectTo(w, r, "/")

	return nil
}
Esempio n. 3
0
func Home(w http.ResponseWriter, r *http.Request) error {
	c, err := cookie.Read(r, "user")
	var userLogin, userAvatarURL string

	if err == nil {
		objectId := c.Values["id"]
		if objectId != "" {
			user := repository.User().FirstByObjectId(objectId)
			if user != nil {
				userLogin = user.Login
				userAvatarURL = user.AvatarURL
			}
		}
	}

	return Templates.ExecuteTemplate(w, "index.html", struct {
		UserLogin     string
		UserAvatarURL string
	}{
		UserLogin:     userLogin,
		UserAvatarURL: userAvatarURL,
	})
}
Esempio n. 4
0
func addMobToUser(user *model.User, mob *model.Mob) error {
	return repository.User().AddMob(user, mob)
}