Skip to content

Instantly share code, notes, and snippets.

func main() {
// Setup The AWS Region and AWS session
conf := &aws.Config{Region: aws.String("eu-west-1")}
mySession := session.Must(session.NewSession(conf))
// Fill App structure with environment keys and session generated
a := App{
CognitoClient: cognito.New(mySession),
UserPoolID: os.Getenv("COGNITO_USER_POOL_ID"),
func (cv *CustomValidator) Validate(i interface{}) error {
if err := cv.validator.Struct(i); err != nil {
// Optionally, you could return the error to give each route more control over the status code
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
return nil
}
func validateUser(sl validator.StructLevel) {
if len(sl.Current().Interface().(User).Username) == 0 || len(sl.Current().Interface().(User).Password) == 0 {
func (a *App) ForgotPassword(c echo.Context) (err error) {
u := new(UserForgot)
if err = c.Bind(u); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
if err = c.Validate(u); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
func (a *App) OTP(c echo.Context) (err error) {
r := new(Response)
o := new(OTP)
if err = c.Bind(o); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
if err = c.Validate(o); err != nil {
return err
func (a *App) Login(c echo.Context) (err error) {
u := new(User)
if err = c.Bind(u); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
if err = c.Validate(u); err != nil {
return err
}
func (a *App) Register(c echo.Context, v validator.Validate) (err error) {
r := new(Response)
u := new(UserRegister)
// Bind the user input saved in context to the u(User) variable and validate it
if err = c.Bind(u); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
if err = c.Validate(u); err != nil {
// Register receiver method is the handler for
// /register endpoint, this method takes echo.Context
// in which is located the user input as json request
// as input with the following format:
// {
// "email":"[email protected]",
// "user":{
// "username":"exampleusername",
// "password":"Hello4world!"
// }
type (
// App struct provides basic information to connect to the
// Cognito UserPool on AWS.
App struct {
CognitoClient *cognito.CognitoIdentityProvider
UserPoolID string
AppClientID string
AppClientSecret string
Token string
}
@fulviodenza
fulviodenza / cognito.go
Created January 18, 2022 12:03
Cognito Auth Operations in Golang
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"os"