Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
API_SECRET=98hbun98h
DB_HOST=127.0.0.1
DB_DRIVER=postgres
DB_USER=postgres
DB_PASSWORD=converge-backend
DB_NAME=goauth
DB_PORT=5432
PORT=8080

TestApiSecret=98hbun9dbhdhhdhdhd8h
TestDbHost=127.0.0.1
TestDbDriver=postgres
TestDbUser=username
TestDbPassword=password
TestDbName=goauth_db_test
TestDbPort=5432
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
.env
deployment-config.txt
1 change: 1 addition & 0 deletions Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: bin/goauth
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,15 @@
# goauth
Go API


- Create a .env file and put these key=values in it:

```
API_SECRET=98hbun98h #Used when creating a JWT. It can be anything
DB_HOST=127.0.0.1
DB_DRIVER=postgres
DB_USER=username
DB_PASSWORD=password
DB_NAME=fullstack_api
DB_PORT=5432
```
6 changes: 4 additions & 2 deletions api/auth/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@ import (
)

// CreateToken func to generate a token with user info
func CreateToken(userID uint32) (string, error) {
func CreateToken(userID uint32, email string, username string) (string, error) {
claims := jwt.MapClaims{}
claims["authorized"] = true
claims["userID"] = userID
claims["email"] = email
claims["username"] = username
claims["exp"] = time.Now().Add(time.Hour * 1).Unix() //Token expires after 1 hour
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(os.Getenv("API_SECRET")))
Expand Down Expand Up @@ -89,4 +91,4 @@ func Pretty(data interface{}) {
}

fmt.Println(string(b))
}
}
11 changes: 6 additions & 5 deletions api/controllers/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import (

"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
"github.com/rs/cors"

_ "github.com/jinzhu/gorm/dialects/postgres" //postgres database driver

"github.com/kwanj-k/goauth/api/models"
)

Expand All @@ -21,7 +21,6 @@ type Server struct {

// Initialize will have our database connection information, initialise our routes
func (server *Server) Initialize(Dbdriver, DbUser, DbPassword, DbPort, DbHost, DbName string) {

var err error
if Dbdriver == "postgres" {
DBURL := fmt.Sprintf("host=%s port=%s user=%s dbname=%s sslmode=disable password=%s", DbHost, DbPort, DbUser, DbName, DbPassword)
Expand All @@ -30,7 +29,7 @@ func (server *Server) Initialize(Dbdriver, DbUser, DbPassword, DbPort, DbHost, D
fmt.Printf("Cannot connect to %s database", Dbdriver)
log.Fatal("This is the error:", err)
} else {
fmt.Printf("We are connected to the %s database", Dbdriver)
fmt.Printf("We are connected to the %s database\n", Dbdriver)
}
}

Expand All @@ -44,5 +43,7 @@ func (server *Server) Initialize(Dbdriver, DbUser, DbPassword, DbPort, DbHost, D
// Run will start our server
func (server *Server) Run(addr string) {
fmt.Println("Listening to port 8080")
log.Fatal(http.ListenAndServe(addr, server.Router))
}
// Use default options
handler := cors.Default().Handler(server.Router)
log.Fatal(http.ListenAndServe(addr, handler))
}
13 changes: 7 additions & 6 deletions api/controllers/login_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ import (
"github.com/kwanj-k/goauth/api/auth"
"github.com/kwanj-k/goauth/api/models"
"github.com/kwanj-k/goauth/api/responses"
"github.com/kwanj-k/goauth/api/utils/formaterror"
"golang.org/x/crypto/bcrypt"
)

// Login func that logins a user and return token
func (server *Server) Login(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
body, err := ioutil.ReadAll(r.Body)
if err != nil {
responses.ERROR(w, http.StatusUnprocessableEntity, err)
Expand All @@ -29,17 +29,18 @@ func (server *Server) Login(w http.ResponseWriter, r *http.Request) {
user.Prepare()
err = user.Validate("login")
if err != nil {
responses.ERROR(w, http.StatusUnprocessableEntity, err)
responses.ERROR(w, http.StatusBadRequest, err)
return
}
token, err := server.SignIn(user.Email, user.Password)
if err != nil {
formattedError := formaterror.FormatError(err.Error())
responses.ERROR(w, http.StatusUnprocessableEntity, formattedError)
var resp = map[string]interface{}{"username": "Wrong email or password"}
responses.JSON(w, http.StatusBadRequest, resp)
return
}
var resp = map[string]interface{}{"status": "Success!"}
resp["token"] = token
resp["email"] = user.Email
responses.JSON(w, http.StatusOK, resp)
}

Expand All @@ -58,5 +59,5 @@ func (server *Server) SignIn(email, password string) (string, error) {
if err != nil && err == bcrypt.ErrMismatchedHashAndPassword {
return "", err
}
return auth.CreateToken(user.ID)
}
return auth.CreateToken(user.ID, user.Email, user.Nickname)
}
3 changes: 2 additions & 1 deletion api/controllers/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"github.com/kwanj-k/goauth/api/middlewares"
)


func (s *Server) initializeRoutes() {

s.Router.StrictSlash(false)
Expand All @@ -27,4 +28,4 @@ func (s *Server) initializeRoutes() {
middlewares.SetMiddlewareAuthentication(s.UpdateUser))).Methods("PUT")
s.Router.HandleFunc("/users/{id}/",
middlewares.SetMiddlewareAuthentication(s.DeleteUser)).Methods("DELETE")
}
}
2 changes: 1 addition & 1 deletion api/middlewares/middlewares.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ func SetMiddlewareAuthentication(next http.HandlerFunc) http.HandlerFunc {
}
next(w, r)
}
}
}
8 changes: 3 additions & 5 deletions api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,15 @@ var server = controllers.Server{}

// Run func to run the server on 8080
func Run() {

var err error
err = godotenv.Load()
if err != nil {
log.Fatalf("Error getting env, not comming through %v", err)
} else {
fmt.Println("We are getting the env values")
}

port := os.Getenv("PORT")
server.Initialize(os.Getenv("DB_DRIVER"), os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD"), os.Getenv("DB_PORT"), os.Getenv("DB_HOST"), os.Getenv("DB_NAME"))
server.Run(":" + port)

server.Run(":8080")

}
}
24 changes: 6 additions & 18 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,26 +1,14 @@
module github.com/kwanj-k/goauth

go 1.13
go 1.14

require (
github.com/badoux/checkmail v0.0.0-20181210160741-9661bd69e9ad
github.com/badoux/checkmail v1.2.1
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/go-openapi/analysis v0.19.6 // indirect
github.com/go-openapi/runtime v0.19.8 // indirect
github.com/go-openapi/spec v0.19.4 // indirect
github.com/go-openapi/validate v0.19.5 // indirect
github.com/go-swagger/go-swagger v0.21.0 // indirect
github.com/gorilla/mux v1.7.3
github.com/jinzhu/gorm v1.9.11
github.com/gorilla/mux v1.8.0
github.com/jinzhu/gorm v1.9.16
github.com/joho/godotenv v1.3.0
github.com/pelletier/go-toml v1.6.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.5.0 // indirect
go.mongodb.org/mongo-driver v1.1.3 // indirect
golang.org/x/crypto v0.0.0-20191122220453-ac88ee75c92c
golang.org/x/net v0.0.0-20191204025024-5ee1b9f4859a // indirect
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e // indirect
golang.org/x/tools v0.0.0-20191205225056-3393d29bb9fe // indirect
github.com/rs/cors v1.7.0
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad
gopkg.in/go-playground/assert.v1 v1.2.1 // indirect
gopkg.in/yaml.v2 v2.2.7 // indirect
)
Loading