Skip to content

Commit

Permalink
Merge pull request #29 from titouanfreville/issue-26-login
Browse files Browse the repository at this point in the history
Beautiful base for 401 errors
  • Loading branch information
Clément authored Mar 7, 2017
2 parents ed59146 + c7270de commit b1427e3
Show file tree
Hide file tree
Showing 13 changed files with 361 additions and 31 deletions.
9 changes: 9 additions & 0 deletions Godeps/Godeps.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

69 changes: 58 additions & 11 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,11 @@ import (
"crypto/rand"
"encoding/base32"
"flag"
"log"
"net/http"

jwt "github.com/dgrijalva/jwt-go"
"github.com/goware/jwtauth"
"github.com/jinzhu/gorm"
"github.com/pressly/chi"
"github.com/pressly/chi/docgen"
"github.com/pressly/chi/middleware"
chiRender "github.com/pressly/chi/render"
"github.com/titouanfreville/popcubeapi/configs"
Expand All @@ -29,9 +26,20 @@ type saveDb struct {
// Key type to be sure the context key is the one we want.
type key string

// Token A JWT Token. Different fields will be used depending on whether you're
// creating or parsing/verifying a token.
// type Token struct {
// Raw string // The raw token. Populated when you Parse a token
// Method SigningMethod // The signing method used or to be used
// Header map[string]interface{} // The first segment of the token
// Claims Claims // The second segment of the token
// Signature string // The third segment of the token. Populated when you Parse a token
// Valid bool // Is the token valid? Populated when you Parse/Verify a token
// }

var (
hmacSampleSecret []byte
tokenAuth *jwtauth.JwtAuth
tokenAuth *JwtAuth
userToken *jwt.Token
encoding = base32.NewEncoding("ybndrfg8ejkmcpqxot1uwisza345h769")
render = renderPackage.New()
Expand All @@ -55,14 +63,15 @@ func newRandomString(length int) string {
func initAuth() {
secret := newRandomString(100)
hmacSampleSecret = []byte(secret)
tokenAuth = jwtauth.New("HS256", hmacSampleSecret, hmacSampleSecret)
tokenAuth = New("HS256", hmacSampleSecret, hmacSampleSecret)
}

// createToken create JWT auth token for current login user
func createToken(user models.User) (string, error) {
claims := jwt.MapClaims{
"name": user.Username,
"email": user.Email,
"role": user.IDRole,
}
unsignedToken := *jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := unsignedToken.SignedString(hmacSampleSecret)
Expand Down Expand Up @@ -140,6 +149,18 @@ func basicRoutes(router *chi.Mux) {
// 422: wrongEntity
// 503: databaseError
router.Post("/login", loginMiddleware)
// swagger:route POST /user Users newPublicUser
//
// New user
//
// This will create an user for organisation if organisation is Public OR Email match parametetered emails
//
// Responses:
// 201: userObjectSuccess
// 422: wrongEntity
// 503: databaseError
// default: genericError
router.Post("/publicuser", newPublicUser)
}

// loginMiddleware login funcion providing user && jwt auth token
Expand Down Expand Up @@ -176,6 +197,32 @@ func loginMiddleware(w http.ResponseWriter, r *http.Request) {

}

func newPublicUser(w http.ResponseWriter, r *http.Request) {
var data struct {
User *models.User
OmitID interface{} `json:"id,omitempty"`
}
store := datastores.Store()

db := dbStore.db
request := r.Body
err := chiRender.Bind(request, &data)
if err != nil || data.User == nil {
render.JSON(w, error422.StatusCode, error422)
} else {
if err := db.DB().Ping(); err == nil {
err := store.User().Save(data.User, db)
if err == nil {
render.JSON(w, 201, data.User)
} else {
render.JSON(w, err.StatusCode, err)
}
} else {
render.JSON(w, error503.StatusCode, error503)
}
}
}

// StartAPI initialise the api with provided host and port.
func StartAPI(hostname string, port string, DbConnectionInfo *configs.DbConnection) {
router := newRouter()
Expand All @@ -202,12 +249,12 @@ func StartAPI(hostname string, port string, DbConnectionInfo *configs.DbConnecti
// Passing -routes to the program will generate docs for the above
// router definition. See the `routes.json` file in this folder for
// the output.
log.Println(docgen.JSONRoutesDoc(router))
log.Println(docgen.BuildDoc(router))
log.Println(docgen.MarkdownRoutesDoc(router, docgen.MarkdownOpts{
ProjectPath: "github.com/titouanfreville/popcubeapi",
Intro: "Welcomme to popcube user api.",
}))
// log.Println(docgen.JSONRoutesDoc(router))
// log.Println(docgen.BuildDoc(router))
// log.Println(docgen.MarkdownRoutesDoc(router, docgen.MarkdownOpts{
// ProjectPath: "github.com/titouanfreville/popcubeapi",
// Intro: "Welcomme to popcube user api.",
// }))

http.ListenAndServe(hostname+":"+port, router)
}
3 changes: 1 addition & 2 deletions api/avatar_route.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"net/http"
"strconv"

"github.com/goware/jwtauth"
"github.com/pressly/chi"
chiRender "github.com/pressly/chi/render"
"github.com/titouanfreville/popcubeapi/datastores"
Expand All @@ -21,7 +20,7 @@ const (
func initAvatarRoute(router chi.Router) {
router.Route("/avatar", func(r chi.Router) {
r.Use(tokenAuth.Verifier)
r.Use(jwtauth.Authenticator)
r.Use(Authenticator)
// swagger:route GET /avatar Avatars getAllAvatar
//
// Get avatars
Expand Down
3 changes: 1 addition & 2 deletions api/channel_route.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"net/http"
"strconv"

"github.com/goware/jwtauth"
"github.com/pressly/chi"
chiRender "github.com/pressly/chi/render"
"github.com/titouanfreville/popcubeapi/datastores"
Expand All @@ -21,7 +20,7 @@ const (
func initChannelRoute(router chi.Router) {
router.Route("/channel", func(r chi.Router) {
r.Use(tokenAuth.Verifier)
r.Use(jwtauth.Authenticator)
r.Use(Authenticator)
// swagger:route GET /channel Channels getAllChannel
//
// Get channels
Expand Down
3 changes: 1 addition & 2 deletions api/emojis_route.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"net/http"
"strconv"

"github.com/goware/jwtauth"
"github.com/pressly/chi"
chiRender "github.com/pressly/chi/render"
"github.com/titouanfreville/popcubeapi/datastores"
Expand All @@ -22,7 +21,7 @@ const (
func initEmojiRoute(router chi.Router) {
router.Route("/emoji", func(r chi.Router) {
r.Use(tokenAuth.Verifier)
r.Use(jwtauth.Authenticator)
r.Use(Authenticator)
// swagger:route GET /emoji Emojis getAllEmoji
//
// Get emojis
Expand Down
3 changes: 1 addition & 2 deletions api/folder_route.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"net/http"
"strconv"

"github.com/goware/jwtauth"
"github.com/pressly/chi"
chiRender "github.com/pressly/chi/render"
"github.com/titouanfreville/popcubeapi/datastores"
Expand All @@ -22,7 +21,7 @@ const (
func initFolderRoute(router chi.Router) {
router.Route("/folder", func(r chi.Router) {
r.Use(tokenAuth.Verifier)
r.Use(jwtauth.Authenticator)
r.Use(Authenticator)
// swagger:route GET /folder Folders getAllFolder
//
// Get folders
Expand Down
Loading

0 comments on commit b1427e3

Please sign in to comment.