This handles authentication for your application.
- username-password based login and register
- schema creation for user
- jwt based token management
In your main function, call auth.Setup() as shown,
package main
import "github.com/bdfp/auth"
func main() {
db, err := sql.Open("mysql", "root:morning_star@/diary")
if err != nil {
panic(err.Error())
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err.Error())
}
log.Println("Database connection opened")
// Set up auth
go auth.Setup(db)
}the following user table is created in the passwed database
| user |
| ------------- |
| id
| username |
| password |
This will also register login and register http handlers as described.Those will run on port 8484.
- Method POST
- Request Object
{ "username": "your_username", "password": "your_password" } - Response Object
{ "token": "eiofgheriuygij wer", "user": { "username": "your_username" } }
- Method POST
- Request Object
{
"username": "your_username",
"password": "your_password"
}
- Response Object
{
"message": "success"
}
In order to secure any route with jwt, just use the auth.Secure(yourHandler) while registering your router
Example:
func startHTTPServer(db *sql.DB) {
router := httprouter.New()
router.POST("/tasks", auth.Secure(myHandler))
log.Fatal(http.ListenAndServe(":8484", router))
}