Category Archives: TUTORIALS

Detailed tutorials explaining how to build most common applications, in different languages.

GraphQL server with Gqlgen and PostgreSQL

 

 

Create graphQL server using gqlgen following gqlgen tutorial

mkdir gqlgen-users
cd gqlgen-users
go mod init github.com/[username]/gqlgen-users

Create tools.go with gqlgen library imported.

tools.go

//go:build tools
// +build tools

package tools

import (
    _ "github.com/99designs/gqlgen"
)

Install packages

go mod tidy

Create the project skeleton

go run github.com/99designs/gqlgen init

 

Create database connector

databaseConnector/databaseConnector.go

package databaseConnector

import (
    "fmt"

    "github.com/jackc/pgtype"
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

type User struct {
    ID       uint   `gorm:"primaryKey"`
    Username string `gorm:"unique"`
    Email    string
    Age      int
    MetaData pgtype.JSONB `gorm:"type:jsonb" json:"fieldnameofjsonb"`
}

func autoMigrateDB(db *gorm.DB) {
    // Perform database migration
    err := db.AutoMigrate(&User{})
    if err != nil {
        fmt.Println(err)
    }
}

func connectToPostgreSQL() (*gorm.DB, error) {
    // dsn := "user=mynews password=test123 dbname=tests host=localhost port=5432 sslmode=disable"
    dsn := "user=toninichev dbname=tests host=localhost port=5432 sslmode=disable"
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
    if err != nil {
        return nil, err
    }

    return db, nil
}

func createuserWithMetaData(db *gorm.DB, username string, email string, age int, metaData string) (*User, error) {
    jsonData := pgtype.JSONB{}
    err := jsonData.Set([]byte(metaData))
    if err != nil {
        return nil, err
    }
    // Create a user
    newUser := User{Username: username, Email: email, Age: age, MetaData: jsonData}
    err = createUser(db, &newUser)
    if err != nil {
        return nil, err
    }
    return &newUser, nil
}
func createUser(db *gorm.DB, user *User) error {
    result := db.Create(user)
    if result.Error != nil {
        return result.Error
    }
    return nil
}

func CreateDB(tableName string) error {
    db, err := connectToPostgreSQL()
    if err != nil {
        return err
    }
    autoMigrateDB(db)
    return nil
}

func CreateUser(username string, email string, age int, metaData string) (*User, error) {
    db, err := connectToPostgreSQL()
    if err != nil {
        return nil, err
    }
    user, err := createuserWithMetaData(db, username, email, age, metaData)
    return user, err
}

func GetUserByID(userID uint) (*User, error) {
    db, err := connectToPostgreSQL()
    if err != nil {
        return nil, err
    }

    var user User
    result := db.First(&user, userID)
    if result.Error != nil {
        return nil, result.Error
    }
    return &user, nil
}

func GetUserByMetaData(metaDataFilter string) (*User, error) {
    db, err := connectToPostgreSQL()
    if err != nil {
        return nil, err
    }

    var user User
    // result := db.First(&user, userID)

    result := db.Where(metaDataFilter).First(&user)

    if result.Error != nil {
        return nil, result.Error
    }
    return &user, nil
}

 

Edit schema adding the new Customer type, queries and mutations to retrieve and create new users.

graph/schema.graphqls

# GraphQL schema example
#
# https://gqlgen.com/getting-started/


type Customer {
  customerId: String!
  username: String!
  email: String!,
  age: Int!
  metaData: String!
}

input NewCustomer {
  customerId: String!
  username: String!
  email: String!,
  age: Int!
  metaData: String!
}

type Query {
  getCustomer(customerId: String!): Customer!
  getCustomerByMetaData(metaData: String!): Customer!
}

type Mutation {
  saveCustomer(input: NewCustomer!):Boolean!
  createDB(tableName: String!):Boolean!
}

Re-generate resolvers with the new schema

go run github.com/99designs/gqlgen generate

Implement the resolvers

graph/schema.resolvers.go

package graph

// This file will be automatically regenerated based on the schema, any resolver implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.44

import (
    "context"
    "strconv"
    "tutorials/gqlgen-users/databaseConnector"
    "tutorials/gqlgen-users/graph/model"
)

// SaveCustomer is the resolver for the saveCustomer field.
func (r *mutationResolver) SaveCustomer(ctx context.Context, input model.NewCustomer) (bool, error) {
    databaseConnector.CreateUser(input.Username, input.Email, input.Age, input.MetaData)
    return true, nil
}

// CreateDb is the resolver for the createDB field.
func (r *mutationResolver) CreateDb(ctx context.Context, tableName string) (bool, error) {
    err := databaseConnector.CreateDB(tableName)

    if err != nil {
        // handle error
        return false, err
    }
    return true, nil
}

// GetCustomer is the resolver for the getCustomer field.
func (r *queryResolver) GetCustomer(ctx context.Context, customerID string) (*model.Customer, error) {
    cid, _ := strconv.Atoi(customerID)
    var customer *databaseConnector.User
    var err error
    customer, err = databaseConnector.GetUserByID(uint(cid))

    if err != nil {
        // handle error
        return nil, err
    }

    // get the underlying byte slice.
    jsonbText, _ := customer.MetaData.Value()
    // Convert byte slice to string
    jsonString := string(jsonbText.([]byte))

    // map returned customer structure from the DB into the model
    c := model.Customer{
        CustomerID: strconv.FormatUint(uint64(customer.ID), 10),
        Username:   customer.Username,
        Email:      customer.Email,
        Age:        customer.Age,
        MetaData:   jsonString,
    }

    return &c, nil
}

// GetCustomerByMetaData is the resolver for the getCustomerByMetaData field.
func (r *queryResolver) GetCustomerByMetaData(ctx context.Context, metaData string) (*model.Customer, error) {
    customer, err := databaseConnector.GetUserByMetaData(metaData)

    if err != nil {
        // handle error
        return nil, err
    }

    // get the underlying byte slice.
    jsonbText, _ := customer.MetaData.Value()
    // Convert byte slice to string
    jsonString := string(jsonbText.([]byte))

    // map returned customer structure from the DB into the model
    c := model.Customer{
        CustomerID: strconv.FormatUint(uint64(customer.ID), 10),
        Username:   customer.Username,
        Email:      customer.Email,
        Age:        customer.Age,
        MetaData:   jsonString,
    }

    return &c, nil
}

// Mutation returns MutationResolver implementation.
func (r *Resolver) Mutation() MutationResolver { return &mutationResolver{r} }

// Query returns QueryResolver implementation.
func (r *Resolver) Query() QueryResolver { return &queryResolver{r} }

type mutationResolver struct{ *Resolver }
type queryResolver struct{ *Resolver }

 

 

Using GORM library to access postgreSQL with JSONB field with GoLang

This tutorial demonstrates how to ‘auto migrate’ the DB and how to store and retrieve data  from JSONB field in postgreSQL database using GoLang.

Auto migrating the DB

In the context of Go programming language and GORM (Go Object Relational Mapping) library, automigration is a feature that automatically creates or updates database tables based on the Go struct definitions.

For the purpose of this example, we will create a table with id, username, email and meta data field. The meta data will be a JSONB field. We could use JSON as well but JSONB is stored in binary format, and although insert operations are slower searching is faster.

In general it is recommended to always use JSONB unless we have a real good reason to use JSON. For example JSON preserves formatting and allows for duplicate keys.

But before we could use JSONB with GORM we have to install the package

go get github.com/jackc/pgtype

Create a connection to PostgreSQL database.

Gorm supports different databases but here will do this exercise with PostgreSQL only.

func connectToPostgreSQL() (*gorm.DB, error) {
    dsn := "user=toninichev dbname=tests host=localhost port=5432 sslmode=disable"
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
    if err != nil {
        return nil, err
    }

    return db, nil
}

Define the structure that will be used to create the the Users table

type User struct {
    ID       uint   `gorm:"primaryKey"`
    Username string `gorm:"unique"`
    Email    string
    Age      int
    MetaData pgtype.JSONB `gorm:"type:jsonb" json:"fieldnameofjsonb"`
}

 

Now let’s create two helper functions that will create a new user:

func createuserWithMetaData(db *gorm.DB, username string, email string, metaData string) User {
    jsonData := pgtype.JSONB{}
    err := jsonData.Set([]byte(metaData))
    if err != nil {
        log.Fatal(err)
    }
    // Create a user
    newUser := User{Username: username, Email: email, Age: 36, MetaData: jsonData}
    err = createUser(db, &newUser)
    if err != nil {
        log.Fatal(err)
    }
    return newUser
}

func createUser(db *gorm.DB, user *User) error {
    result := db.Create(user)
    if result.Error != nil {
        return result.Error
    }
    return nil
}

And let’s put it all together:

The entire code

package main

import (
    "log"

    "github.com/jackc/pgtype"
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

type User struct {
    ID       uint   `gorm:"primaryKey"`
    Username string `gorm:"unique"`
    Email    string
    Age      int
    MetaData pgtype.JSONB `gorm:"type:jsonb" json:"fieldnameofjsonb"`
}

func connectToPostgreSQL() (*gorm.DB, error) {
    dsn := "user=toninichev dbname=tests host=localhost port=5432 sslmode=disable"
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
    if err != nil {
        return nil, err
    }

    return db, nil
}

func createuserWithMetaData(db *gorm.DB, username string, email string, metaData string) User {
    jsonData := pgtype.JSONB{}
    err := jsonData.Set([]byte(metaData))
    if err != nil {
        log.Fatal(err)
    }
    // Create a user
    newUser := User{Username: username, Email: email, Age: 36, MetaData: jsonData}
    err = createUser(db, &newUser)
    if err != nil {
        log.Fatal(err)
    }
    return newUser
}

func createUser(db *gorm.DB, user *User) error {
    result := db.Create(user)
    if result.Error != nil {
        return result.Error
    }
    return nil
}

func getUserByID(db *gorm.DB, userID uint) (*User, error) {
    var user User
    result := db.First(&user, userID)
    if result.Error != nil {
        return nil, result.Error
    }
    return &user, nil
}

func updateUser(db *gorm.DB, user *User) error {
    result := db.Save(user)
    if result.Error != nil {
        return result.Error
    }
    return nil
}

func deleteUser(db *gorm.DB, user *User) error {
    result := db.Delete(user)
    if result.Error != nil {
        return result.Error
    }
    return nil
}

func autoMigrateDB(db *gorm.DB) {
    // Perform database migration
    err := db.AutoMigrate(&User{})
    if err != nil {
        log.Fatal(err)
    }
}

func main() {

    db := func() *gorm.DB {
        db, err := connectToPostgreSQL()
        if err != nil {
            log.Fatal(err)
        }
        return db
    }()

    autoMigrateDB(db)

    //CRUD operations

    func() {
        newUser := createuserWithMetaData(db, "Toni", "toni@gmail.com", `{"key": "value", "days":[{"dayOne": "1"}], "user-id": "1"}`)
        log.Println("Created user:", newUser)
    }()

    func() {
        newUser := createuserWithMetaData(db, "John", "john@gmail.com", `{"key": "value two", "days":[{"dayOne": "2"}], "user-id": "2"}`)
        log.Println("Created user:", newUser)
    }()

    func() {
        newUser := createuserWithMetaData(db, "Sam", "sam@gmail.com", `{"key": "value three", "days":[{"dayOne": "3"}], "user-id": "3"}`)
        log.Println("Created user:", newUser)
    }()

    // Query user by ID
    user, err := getUserByID(db, 2)
    if err != nil {
        log.Fatal(err)
    }
    log.Println("User by ID:", user)

    var result User
    db.Where("meta_data->>'user-id' = ?", "2").First(&result)
    log.Println(result)
}

 

Updates

We can use byte type instead of pgtype libray which simplifies the code a bit.

type Users struct {
    ID       uint   `gorm:"primaryKey"`
    Username string `gorm:"unique"`
    MetaData []byte `gorm:"type:jsonb" json:"meta-data"`
}

 

func createuserWithMetaData(db *gorm.DB) bool {
    metaData := "{\"one\":\"1\"}"
    // Create a user
    newUser := Users{
        Username: "TEST 123",
        MetaData: []byte(metaData),
    }

    db.Create(&newUser)

    return true
}

 

Authenticate user with JWT in GoLang

  https://ToniNichev@github.com/ToniNichev/tutorials-golang-authanticate-with-jwt.git

 

Generating JWT for testing

Sign, Verify and decode JWT

Setting up the project

we are going to use Gin Web framework to create simple HTTP server that we could query against, passing JWT in the header and then using secret or public key to validate the signature.

package main

import (
    "github.com/gin-gonic/gin"
)

func AuthMiddleware() gin.HandlerFunc {
    // In a real-world application, you would perform proper authentication here.
    // For the sake of this example, we'll just check if an API key is present.
    return func(c *gin.Context) {
        apiKey := c.GetHeader("X-Auth-Token")
        if apiKey == "" {
            c.AbortWithStatusJSON(401, gin.H{"error": "Unauthorized"})
            return
        }
        c.Next()
    }
}

func main() {
    // Create a new Gin router
    router := gin.Default()

    // Public routes (no authentication required)
    public := router.Group("/public")
    {
        public.GET("/info", func(c *gin.Context) {
            c.String(200, "Public information")
        })
        public.GET("/products", func(c *gin.Context) {
            c.String(200, "Public product list")
        })
    }

    // Private routes (require authentication)
    private := router.Group("/private")
    private.Use(AuthMiddleware())
    {
        private.GET("/data", func(c *gin.Context) {
            c.String(200, "Private data accessible after authentication")
        })
        private.POST("/create", func(c *gin.Context) {
            c.String(200, "Create a new resource")
        })
    }

    router.POST("query", AuthMiddleware(), validateSession, returnData)

    // Run the server on port 8080
    router.Run(":8080")
}

We added validateSession middleware that will decode the token and verify the signature.

 

Creating JWT services to decode and validate signature

We are using jwt GoLang library to decode the token, and validate the signature.

There are two ways to encode JWT: using symmetric encryption (meaning that the same secret is used to sign and validate the signature. This is done in retreiveTokenWithSymmetrikKey and retreiveTokenWithAsymmetrikKey is used to validate signature using the public key from the private/public key pair used to sign the token.

 

package main

import (
    "bytes"
    "encoding/json"
    "errors"
    "fmt"
    "io/ioutil"

    "github.com/gin-gonic/gin"
    "github.com/golang-jwt/jwt/v5"
)

type User struct {
    name  string
    email string
}

var user User

type requestBody struct {
    OperationName *string     `json:"operationName"`
    Query         *string     `json:"query"`
    Variables     interface{} `json:"variables"`
}

func validateSession(c *gin.Context) {
    user.name = ""
    user.email = ""
    if c.Request.Body != nil {
        bodyBytes, _ := ioutil.ReadAll(c.Request.Body)
        c.Request.Body.Close()
        c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))

        body := requestBody{}
        if err := json.Unmarshal(bodyBytes, &body); err != nil {
            return
        }

        // extract the token from the headers
        tokenStr := c.Request.Header.Get("X-Auth-Token")

        product := body.Variables.(map[string]interface{})["product"]

        var payload string
        var err error
        if product == "web" {
            payload, err = retreiveTokenWithSymmetrikKey(c, tokenStr)
        } else {
            payload, err = retreiveTokenWithAsymmetrikKey(c, tokenStr)
        }

        if err != nil {
            c.AbortWithStatusJSON(401, gin.H{"error": "Session token signature can't be confirmed!"})
        }

        if payload == "" {
            c.AbortWithStatusJSON(401, gin.H{"error": "Invalid token"})
            return
        }
        c.Next()
    }

}

func retreiveTokenWithSymmetrikKey(c *gin.Context, tokenStr string) (string, error) {
    fmt.Println("retreive Token With Symmetric Key ...")

    tknStr := c.Request.Header.Get("X-Auth-Token")
    secretKey := "itsasecret123"

    token, err := jwt.Parse(tknStr, func(token *jwt.Token) (interface{}, error) {
        return []byte(secretKey), nil
    })

    if err != nil {
        c.AbortWithStatusJSON(401, gin.H{"error": "Session token signature can't be confirmed!"})
        return "", errors.New("session token signature can't be confirmed!")
    } else {
        claims := token.Claims.(jwt.MapClaims)
        fmt.Println("======================================")
        fmt.Println(claims)
        fmt.Println(claims["author"])
        fmt.Println(claims["data"])
        fmt.Println("======================================")
        user.name = claims["author"].(string)
    }
    return "token valid", nil
}

func retreiveTokenWithAsymmetrikKey(c *gin.Context, tokenStr string) (string, error) {

    fmt.Println("retreive Token With Asymmetric Key ...")

    publicKeyPath := "key/public_key.pem"
    keyData, err := ioutil.ReadFile(publicKeyPath)
    if err != nil {
        c.AbortWithStatusJSON(401, gin.H{"error": "Error reading public key"})
        return "", errors.New("error reading public key")
    }

    var parsedToken *jwt.Token

    // parse token
    state, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {

        // ensure signing method is correct
        if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
            c.AbortWithStatusJSON(401, gin.H{"error": "Session token signature can't be confirmed!"})
            return nil, errors.New("unknown signing method")
        }

        parsedToken = token

        // verify
        key, err := jwt.ParseRSAPublicKeyFromPEM([]byte(keyData))
        if err != nil {
            return nil, errors.New("parsing key failed")
        }

        return key, nil
    })

    claims := state.Claims.(jwt.MapClaims)

    fmt.Println("======================================")
    fmt.Println("Header [alg]:", parsedToken.Header["alg"])
    fmt.Println("Header [expiresIn]:", parsedToken.Header["expiresIn"])
    fmt.Println("Claims [author]:", claims["author"])
    fmt.Println("Claims [data]:", claims["data"])
    fmt.Println("======================================")
    user.name = claims["author"].(string)

    if !state.Valid {
        return "", errors.New("verification failed")
    }

    if err != nil {
        return "", errors.New("unknown signing error")
    }

    return "token valid", nil
}

func returnData(c *gin.Context) {
    fmt.Println("Returning data ...")
    c.String(200, user.name)
}

 

 

Making requests with JWT

We are going to use Postman to make a new POST request passing the JWT

Generate JWT

Open the second project: Sign, Verify and decode JWT

Make sure that you comment and uncomment the right type of token that you want to use: asymmetric vs symmetric.
Run the project yarn start end copy the long string printed right after SIGNED JWT.

Create new postman POST request

Open Postman and create new POST request. In the url put http://localhost:8080/query this is where our Gin Web server running.

Add X-Auth-Token JWT

Open header section, and add X-Auth-Token key with the value the JWT copied from Sign, Verify and decode JWT

 

Add query parameters and variables.

We are going to pass dummy parameters just for testing except for product
We are going to use product parameter to distinguish between symmetric and asymmetric tokens.
Let’s assume that our app will except symmetric tokens for web and asymmetric for app so make sure that you will pass the right JWT.
Navigate to the GraphQL section of the request, and add the query and the variables.

query

query GetCustomerReccomendations($customerId: String!, $organization: organization!, $product: String!) {
    getCustomer(customerId: $customerId) {
        customerId
        zipCode
        }
    }
}

variables

{
    "customerId": "2b59f049-04d1-43d5-ac87-8ac62069d932",
    "organization": "nbcnews",
    "product": "app"
}

 

Make the request and check the response

If everything works good, you will see the user name printed in the response.

Sign, Verify and decode JWT

  https://github.com/ToniNichev/tutorials-encodeDecodeJWT

Json Web Token become widely popular for creating data with optional signature and/or optional encryption and payload.

JWTs are a Base64 encoded string with a signature attached to it. JWT components are separated by . The components are:

  • Header: Contains metadata about the token, such as the signing algorithm used.
  • Payload: Contains the claims, which are statements about the subject of the token. For example, a JWT might contain claims about a user’s identity, such as their username and email address, or their authorization to access certain resources.
  • Signature: A digital signature that ensures the integrity of the header and payload. The signature is created using the header and payload and a secret key known only to the issuer.

Example token:

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdXRob3IiOiJUb25pIFkgTmljaGV2IiwiaWF0IjoxNzA2MTEzNDc0LCJkYXRhIjoiTmV3IEpXVCBnZW5lcmF0ZWQgYXQgV2VkIEphbiAyNCAyMDI0IDExOjI0OjM0IEdNVC0wNTAwIChFYXN0ZXJuIFN0YW5kYXJkIFRpbWUpIiwiZXhwIjoxNzA2MTU2Njc0LCJhdWQiOiJodHRwczovL215c29mdHdhcmUtY29ycC5jb20iLCJpc3MiOiJUb25pIE5pY2hldiIsInN1YiI6InRvbmkubmljaGV2QGdtYWlsLmNvbSJ9.YVDqPvei911_KpPjywiZzzK4vNZAm0wiFC0jMV3qI8eUIuPsJC48GkhjNQFgG3GIqHvkwuWmmZEmpD6UrrxENtw9M8h-iLG9syWMJh1HqsyfpKzdATr3PY7fGE1W9If9v0ULWT7ogO_dMuquEf1vi1PcdW-YjrMqZtSnPbIrgaHogeFd3Hix2Bdmlf8v2TX9CWZHJYbgcTj9xDKFw92GkPgeuqYZ2I0C_2VbsWAjLWmdG5iOQakY7XS2I39qCCd87JLsxXHTfmK4mpMBIUgyOaBIy-o7kfQ1hU5wb-DA0H-GtG-WAgyfpIfw0kgULxV-paVVXQLurv78Lm7x6k5B1g

Let’s do base64 decode on each part of the token above:

Header

echo 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9' |base64 -d
{"alg":"RS256","typ":"JWT"}%
  • “alg”: “RS256” – the encrypting algorithm
  • “typ”: “JWT” – type of the token

Payload

echo 'eyJhdXRob3IiOiJUb25pIFkgTmljaGV2IiwiaWF0IjoxNzA2MTEzNDc0LCJkYXRhIjoiTmV3IEpXVCBnZW5lcmF0ZWQgYXQgV2VkIEphbiAyNCAyMDI0IDExOjI0OjM0IEdNVC0wNTAwIChFYXN0ZXJuIFN0YW5kYXJkIFRpbWUpIiwiZXhwIjoxNzA2MTU2Njc0LCJhdWQiOiJodHRwczovL215c29mdHdhcmUtY29ycC5jb20iLCJpc3MiOiJUb25pIE5pY2hldiIsInN1YiI6InRvbmkubmljaGV2QGdtYWlsLmNvbSJ9' |base64 -d
{"author":"Toni Y Nichev","iat":1706113474,"data":"New JWT generated at Wed Jan 24 2024 11:24:34 GMT-0500 (Eastern Standard Time)","exp":1706156674,"aud":"https://mysoftware-corp.com","iss":"Toni Nichev","sub":"toni.nichev@gmail.com"}

Signature

echo 'YVDqPvei911_KpPjywiZzzK4vNZAm0wiFC0jMV3qI8eUIuPsJC48GkhjNQFgG3GIqHvkwuWmmZEmpD6UrrxENtw9M8h-iLG9syWMJh1HqsyfpKzdATr3PY7fGE1W9If9v0ULWT7ogO_dMuquEf1vi1PcdW-YjrMqZtSnPbIrgaHogeFd3Hix2Bdmlf8v2TX9CWZHJYbgcTj9xDKFw92GkPgeuqYZ2I0C_2VbsWAjLWmdG5iOQakY7XS2I39qCCd87JLsxXHTfmK4mpMBIUgyOaBIy-o7kfQ1hU5wb-DA0H-GtG-WAgyfpIfw0kgULxV-paVVXQLurv78Lm7x6k5B1g' |base64 -d
aP�>���]*����2���@�L"-#1]�#ǔ"��$.<Hc5`��{��妙�&�>���D6�=3�~����%�&G�̟���:�=��MV���E
                                                                                  Y>���2��o�S�uo���*fԧ=�+����]�x��f��/�5�       fG%��q8��2��݆����؍�e[�`#-i��A��t�#'|���q�~b���!H29�H��;��5�Npo�����o�
                                                                                                                                                                                                    �����H/~��U]���.n��NA%

Obviously there is no readable text here.

As we see JWT payload is not encrypted and could be decoded with any base64 decoder so never store sensitive data there. The purpose of signing with our private key is to make sure that ‘audience’ (who ever is going to use the token) will be able to verify the authenticity of this token with shared public key.

Claims to Verify

When code is presented with a JWT, it should verify certain claims. At a minimum, these claims should be checked out:

  • iss identifies the issuer of the JWT. (UUID, domain name, URL or something else)
  • aud identifies the audience of the token, that is, who should be consuming it. aud may be a scalar or an array value.
  • nbf and exp. These claims determine the timeframe for which the token is valid.

It doesn’t matter exactly what this strings are as long as the issuer and consumer of the JWT agree on the values.

JWT signing algorithms.

The default algorithm used is (HS256) which is symmetric: meaning that the same ‘secret’ is used for signing and verifying. In the example below  `itsasecret123`

Symmetric algorithm

jwt-services-symmetric.js
import jwt from "jsonwebtoken";
import fs from "fs";

const now = Math.round(new Date().getTime() / 1000);
const expirationTime = now + 500; // Set to 15 minutes (900 seconds)

const secret = 'itsasecret123';

const sign = async (signData, payload) => {
  // Create the JWT header and payload
  const header = {
    'alg': 'RS256',
    'typ': 'JWT'
  };


  const token = jwt.sign(payload, secret);
  return token;
}

const verify = async (token, signData) => {

  try {
    return jwt.verify(token, secret);
  } catch (err) {
    console.log("Error: ", err);
    return false;
  }

}

const decode = async (token) => {
  return jwt.decode(token, {complete: true});
}
export default {
  sign,
  verify,
  decode,
}

 

Asymmetric algorithm

With asymmetric algorithms like (RS256) we use private key to sign the token, and public key to verify the signature. 

How to create public/private key pair:

using opensssl:

  1. Generate the Key Pair:
    openssl genrsa -out private_key.pem 2048
  2. Extract the Public Key
    openssl rsa -in private_key.pem -pubout -out public_key.pem
  3. Secure the Private Key with passphrase (optional but highly recommended)
    openssl rsa -aes256 -in private_key.pem -out private_key_protected.pem

jwt-services-asymmetric.js

import jwt from "jsonwebtoken";
import fs from "fs";

const now = Math.round(new Date().getTime() / 1000);
const expirationTime = now + 500; // Set to 15 minutes (900 seconds)

const privateKey = fs.readFileSync('./keys/private_key.pem');
const publicKey = fs.readFileSync('./keys/public_key.pem');

const sign = async (signData, payload) => {
  // Create the JWT header and payload
  const header = {
    'alg': 'RS256',
    'typ': 'JWT'
  };


  // SIGNING OPTIONS
  const signOptions = {
    issuer: signData.issuer,
    subject: signData.subject,
    audience: signData.audience,
    expiresIn: signData.expiresIn,
    algorithm: signData.algorithm,
  };


  const token = jwt.sign(payload, privateKey, signOptions);
  return token;
}

const verify = async (token, signData) => {
  // VERIFY OPTIONS
  const verifyOptions = {
    issuer: signData.issuer,
    subject: signData.subject,
    audience: signData.audience,
    expiresIn: signData.expiresIn,
    algorithm: signData.algorithm,
  };

  try {
    return jwt.verify(token, publicKey, verifyOptions);
  } catch (err) {
    console.log("Error: ", err);
    return false;
  }

}

const decode = async (token) => {
  return jwt.decode(token, {complete: true});
}
export default {
  sign,
  verify,
  decode,
}

Calling the services. Uncomment jwt-services-symmetric .js and comment the other one if you want to test the symmetric JWT sign.

index.js

import jwt from "./jwt-services-asymmetric.js";
//import jwt from "./jwt-services-symmetric.js";

const now = Math.round(new Date().getTime() / 1000);
const secret = "12345";

const signData = {
    issuer: 'Toni Nichev',
    subject: 'toni.nichev@gmail.com',
    audience: 'https://mysoftware-corp.com',
    expiresIn: "12h",
    algorithm: "RS256"
}

const date = new Date();
let dateStr = date.toString();

const payload = {
    "author": "Toni Y Nichev",
    "iat": now,
    "data": `New JWT generated at ${dateStr}`,
};


const token = await jwt.sign(signData, payload);
console.log(`\n==================\nSIGN JWT\n==================\n ${token}`);



const v = await jwt.verify(token, signData);
console.log(`\n==================\nVERIFY SIGNATURE\n==================\n`, v);


const d = await jwt.decode(token);
console.log(`\n==================\nDECODE\n==================\n`, d);

 

Adding Google sign-in in iOS with SwiftUI

 

 Git Hub Repo

Google also has a great tutorial here: Get started with Google Sign-In for iOS and macOS

Pre-requirements:

Create authorization credentials.

This is covered in another article here.

Install GoogleSignIn and GoogleSignInWithSwiftSupport

Covered here

Short cheatsheet below:

  1. If you don’t already have CocoaPods installed, follow the steps in the CocoaPods Getting Started guide.
  2. Open a terminal window and navigate to the location of your app’s Xcode project.
  3. If you have not already created a Podfile for your application, create one now:
    pod init
  4. Open the Podfile created for your application and add the following:
    pod 'GoogleSignIn'
  5. If you are using SwiftUI, also add the pod extension for the “Sign in with Google” button:
    pod 'GoogleSignInSwiftSupport'
  6. Save the file and run:
    pod install
  7. From now on Open the generated .xcworkspace workspace file for your application in Xcode. Use this file for all future development on your application. (Note that this is different from the included .xcodeproj project file, which would result in build errors when opened.)
  8. Now we are almost ready to start coding, but when we build the project we might (or might not depends of X-code version) face some issues..

Fixing error rsync.samba(4644) deny(1) file-write-create

Navigate to the Build Settings, find ‘User Script Sandboxing’ and

Flip it to No

Fixing “Your app is missing support for the following URL schemes:”

Copy missing scheme from the error message and add it in the info->url section

 

Let’s get started

 

Adding Google Client ID (GIDClientID)

Ether you face the problems before or not this is one thing that is mandatory.

 

1. Adding UserAuthModel to share between all views.

If you don’t know how to do this read about ObservableObject and @Published and sharing data between Views.

This class has to conform to the ObservableObject in order to have its properties reflecting the View.
We will create methods to check if user is signed in, and update shared parameters: givenName, userEmail, isLoggedIn …

import SwiftUI
import GoogleSignIn
import GoogleSignInSwift

final class UserAuthModel: ObservableObject {
    @Published var givenName: String = ""
    @Published var isLoggedIn: Bool = false
    @Published var errorMessage: String = ""
    @Published var userEmail: String = ""
    @Published var profilePicUrl: String = ""
    
    init() {
        check()
    }
    
    func getUserStatus() {
        if GIDSignIn.sharedInstance.currentUser != nil {
            let user = GIDSignIn.sharedInstance.currentUser
            guard let user = user else { return }
            let givenName = user.profile?.givenName
            self.givenName = givenName ?? ""
            self.userEmail = user.profile!.email
            self.profilePicUrl = user.profile!.imageURL(withDimension: 100)!.absoluteString
            
            self.isLoggedIn = true
        } else {
            self.isLoggedIn = false
            self.givenName = "Not Logged In"
        }
    }
    
    func check() {
        GIDSignIn.sharedInstance.restorePreviousSignIn { user, error in
            if let error = error {
                self.errorMessage = "error: \(error.localizedDescription)"
            }
            self.getUserStatus()
            
        }
    }
    
    func gertRootViewController() -> UIViewController {
        guard let screen = UIApplication.shared.connectedScenes.first as? UIWindowScene else {
            return .init()
        }
        guard let root = screen.windows.first?.rootViewController else {
            return .init()
        }
        return root
    }
    
    
    func signIn() {
        GIDSignIn.sharedInstance.signIn(withPresenting: gertRootViewController()) { signInResult, error in
            guard let result = signInResult else {
                // Inspect error
                print("Error occured in signIn()")
                return
            }
            print("Signing in ...")
            print(result.user.profile?.givenName ?? "")
            self.getUserStatus()
        }
    }
    
    func signOut() {
        GIDSignIn.sharedInstance.signOut()
        self.getUserStatus()
    }
    

 

Now let’s edit the app starter and put  userAuthModel in the environmentObject

//
//  SignInWithGoogleTutorialApp.swift
//  SignInWithGoogleTutorial
//
//  Created by Toni Nichev on 1/3/24.
//

import SwiftUI

@main
struct SignInWithGoogleTutorialApp: App {
    
    @StateObject var userAuthModel: UserAuthModel = UserAuthModel()
    
    var body: some Scene {
        WindowGroup {
            NavigationView {
                ContentView()
            }
            .environmentObject(userAuthModel)
        }
    }
}

 

Adding Sign In / Sign Out buttons to the View

//
//  ContentView.swift
//  SignInWithGoogleTutorial
//
//  Created by Toni Nichev on 1/3/24.
//

import SwiftUI

struct ContentView: View {
    
    @EnvironmentObject var userAuthModel: UserAuthModel
    
    fileprivate func signInButton() -> some View {
        HStack {
            Image("GoogleSignInButton")
                .resizable()
                .frame(width: 50, height: 50)
            
            Button(action: {
                userAuthModel.signIn()
            }, label: {
                Text("Sign In")
            })
        }
    }
    
    fileprivate func signOutButton() -> Button<Text> {
        Button(action: {
            userAuthModel.signOut()
        }, label: {
            Text("Sign Out")
        })
    }
    
    fileprivate func profilePic() -> some View {
        AsyncImage(url: URL(string: userAuthModel.profilePicUrl))
            .frame(width: 100,height: 100)
    }
    
    var body: some View {
        VStack {
            if userAuthModel.isLoggedIn {
                profilePic()
                Text("Hello: \(userAuthModel.givenName)")
                signOutButton()
            } else {
                signInButton()
            }
            
        }
    }
}

#Preview {
    ContentView().environmentObject(UserAuthModel())
}

We have to also edit the #Preview and add userAuthModel there so the preview won’t break.

Adding Authentication with a backend server

Google article

The purpose of authentication on the backend server is to make sure that logged-in users could have access to some protected content, like subscriptions, pro-articles, etc.

Once the user signs-in in the native app, the app sends the id-token to the backend, and the backend validates the token and could return access-token back to the app.

In the previous chapter we added UserAuthModel.swift file.
This is the place to call the backend server.

func sendTokenToBackendServer() {
    
    let user = GIDSignIn.sharedInstance.currentUser
    guard let user = user else { return }
    let stringToken = user.idToken!.tokenString
    
    
    guard let authData = try? JSONEncoder().encode(["idToken" : stringToken]) else {
        return
    }
    
    let url = URL(string: "https://regexor.net/examples/google-sign-in-server-notification/")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    
    
    let task = URLSession.shared.uploadTask(with: request, from: authData) { data, response, error in
        print(response ?? ".")
        // handle response from my backend.
        if error != nil {
            print("Error: \(String(describing: error))")
        }
        
        // Handle the response from the server
        let dataString = String(data: data!, encoding: .utf8)
        print ("got data: \(dataString!)")

    }
    
    task.resume()
}

and the final UserAuthenticationModel.swift will look like this:

import SwiftUI
import GoogleSignIn
import GoogleSignInSwift

final class UserAuthModel: ObservableObject {
    @Published var givenName: String = ""
    @Published var isLoggedIn: Bool = false
    @Published var errorMessage: String = ""
    @Published var userEmail: String = ""
    @Published var profilePicUrl: String = ""
    
    
    init() {
        check()
    }
    
    func getUserStatus() {
        if GIDSignIn.sharedInstance.currentUser != nil {
            let user = GIDSignIn.sharedInstance.currentUser
            guard let user = user else { return }
            let givenName = user.profile?.givenName
            self.givenName = givenName ?? ""
            self.userEmail = user.profile!.email
            self.profilePicUrl = user.profile!.imageURL(withDimension: 100)!.absoluteString
            
            self.isLoggedIn = true
        } else {
            self.isLoggedIn = false
            self.givenName = "Not Logged In"
        }
    }
    
    func check() {
        GIDSignIn.sharedInstance.restorePreviousSignIn { user, error in
            if let error = error {
                self.errorMessage = "error: \(error.localizedDescription)"
            }
            self.getUserStatus()
            
        }
    }
    
    func gertRootViewController() -> UIViewController {
        guard let screen = UIApplication.shared.connectedScenes.first as? UIWindowScene else {
            return .init()
        }
        guard let root = screen.windows.first?.rootViewController else {
            return .init()
        }
        return root
    }
    
    
    func signIn() {
        GIDSignIn.sharedInstance.signIn(withPresenting: gertRootViewController()) { signInResult, error in
            guard let result = signInResult else {
                // Inspect error
                print("Error occured in signIn()")
                return
            }
            print("Signing in ...")
            print(result.user.profile?.givenName ?? "")
            self.getUserStatus()
            self.sendTokenToBackendServer()
        }
    }
    
    func signOut() {
        GIDSignIn.sharedInstance.signOut()
        self.getUserStatus()
    }
    
    func sendTokenToBackendServer() {
        
        let user = GIDSignIn.sharedInstance.currentUser
        guard let user = user else { return }
        let stringToken = user.idToken!.tokenString
        
        
        guard let authData = try? JSONEncoder().encode(["idToken" : stringToken]) else {
            return
        }
        
        let url = URL(string: "https://regexor.net/examples/google-sign-in-server-notification/")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        
        
        let task = URLSession.shared.uploadTask(with: request, from: authData) { data, response, error in
            print(response ?? ".")
            // handle response from my backend.
            if error != nil {
                print("Error: \(String(describing: error))")
            }
            
            // Handle the response from the server
            let dataString = String(data: data!, encoding: .utf8)
            print ("got data: \(dataString!)")

        }
        
        task.resume()
    }
}

 

Server script to get idToken form the native app:
In the example below we Just save the token to a file. In real life scenario, here we have to verify the identity of the id token before sending the access-token back to the app.

<?php

// SAVE RAW DATA
$appleData = file_get_contents('php://input');
// Just saves the token to a file.
// In real life scenario, here we have to verify the identity of the id token before sending the access-token back to the app
$file = fopen("./data.txt", "a");
fwrite($file, $appleData);
fclose($file);

echo "send something back to the native app like acccess-token";

 

Using EnvironmentObject to share data between views

//
//  ContentView.swift
//  Test
//
//  Created by Toni Nichev on 1/3/24.
//

import SwiftUI


// Our observable object class
class GameSettings: ObservableObject {
    @Published var scoree = 0
    var test = 4
}

// A view that expects to find a GameSettings object
// in the environment, and shows its score.
struct ScoreView: View {
    // 2: We are not instantiating gameSetting here since it's already done in ContentView. 
    @EnvironmentObject var gameSettings: GameSettings
    
    var body: some View {
        Text("Score: \(gameSettings.scoree)")
        Text("Test: \(gameSettings.test)")
    }
}

struct ContentView: View {
    // 1: We instantiate GameSettings only here and pass it to the environmentObject at the end
    @StateObject var gameSettings = GameSettings()
    var body: some View {
        NavigationStack {
            VStack {
                Image(systemName: "globe")
                    .imageScale(.large)
                    .foregroundStyle(.tint)
                
                Button("Increase score") {
                    gameSettings.scoree += 1
                    gameSettings.test += 1
                }
                
                NavigationLink {
                    ScoreView()
                } label: {
                    Text("Show score")
                }
            }
        }
        .environmentObject(gameSettings)
    }
}

#Preview {
    ContentView()
}

#Preview {
    ScoreView().environmentObject(GameSettings())
}

 

Set up GraphQL with gqlgen and golang

The goal: setting up GraphQL server using Gqlgen library.
We are going to set up GraphQL server with Users, and create queries to retrieve the users by id or user name.

Schema-first approach – means that instead of using library apis (code-first approach) we are going to write our schema manually using the GraphQL schema definition language.

Setting up the project

  • Create project directory
    mkdir gqlgen-tutorial
  • Navigate to the folder
    cd gqlgen-tutorial
  • Initialize go project.
    go mod init gqlgen-tutorial
  • Create tools.go and add gqlgen  library
//go:build tools
// +build tools

package tools

import _ "github.com/99designs/gqlgen"
  • Add the library
    go mod tidy

Initializing Gqlgen with boilerplate schema and resolvers

gqlgen has handy command to Initialize gqlgen config and generate the models.

go run github.com/99designs/gqlgen init

This will create server.go the server starting point and ./graph directory with a couple of files including schema.graphqls and if you open it you will see that it comes with pre-defined example schema which we are going to remove later and start from scratch.

graph/model/model_gen.go – is auto generated file containing structure of defined by the schema file graph/schema.graphqls

graph/generated.go – this is a file with generated code that injects context and middleware for each query and mutation.

We should not modify these files since they will be modified by gqlgen as we update the schema. Instead, we should edit these files:

graph/schema.graphqls –  GraphQL schema file where types, queries, and mutations are defined.

graph/resolver.go – resolver functions for queries and mutations defined in schema.graphqls

At this point we could start the server and see the playground and the schema.

go run ./server.go

Sometimes you might see an error and in this case just run go mod tidy again.

Defining queries

First let’s remove boilerplate schema from graph/schema.graphqls and add our new schema

graph/schema.graphqls

# GraphQL schema example
#
# https://gqlgen.com/getting-started/


type User {
  id: ID!
  name: String!
  userType: String!
}

type Query {
  getUser(id:ID!): User
}

input NewUser {
  userId: String!
  userName: String!
  userType: String!
}

type Mutation {
  createUser(input: NewUser!): User!
}

 

Generate code and running the API

We will now generate code, which will update the following files using the information we provided in the schema file:

  • schema.resolvers.go
  • model/models_gen.go
  • generated/generated.go

Delete the example code in schema.resolvers.go and then run the following command:

go run github.com/99designs/gqlgen generate

If we run the server we will run into an error because we didn’t define any resolver yet.

Defining the backend to fetch and store values

In resolver.go:

– import qlgen-tutorial/graph/model.  line: 3
– declare a Hash Map that we will use to store users. Line 10

package graph

import "gqlgen-tutorial/graph/model"

// This file will not be regenerated automatically.
//
// It serves as dependency injection for your app, add any dependencies you require here.

type Resolver struct{
    UsersStore map[string]model.User	
}

 

We defined UserStore of type map which essentially is a hash-map with keys of type string and values of type model.User.

In schema.resolvers.go, we are going to modify the boilerplate methods: CreateUser and GetUser

package graph

// This file will be automatically regenerated based on the schema, any resolver implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.24

import (
    "context"
    "fmt"
    "gqlgen-tutorial/graph/model"
)

// CreateUser is the resolver for the createUser field.
func (r *mutationResolver) CreateUser(ctx context.Context, input model.NewUser) (*model.User, error) {

    // create new user to be added in r.Resolver.UsersStore and returned
    var user model.User

    if len(r.Resolver.UsersStore) == 0 {
        // create new UserStore hash map if it does not exist
        r.Resolver.UsersStore = make(map[string]model.User)
    }
    // set up new user attributes
    user.ID = input.UserID
    user.Name = input.UserName
    user.UserType = input.UserType

    // adds newly created user into the resolver's UserStore
    r.Resolver.UsersStore[input.UserID] = user

    return &user, nil
}

// GetUser is the resolver for the getUser field.
func (r *queryResolver) GetUser(ctx context.Context, id string) (*model.User, error) {

    fmt.Println(r.Resolver.UsersStore)

    // retrieve user from  the store
    user, isOk := r.Resolver.UsersStore[id]
    if !isOk {
        return nil, fmt.Errorf("not found")
    }
    return &user, nil
}

// Mutation returns MutationResolver implementation.
func (r *Resolver) Mutation() MutationResolver { return &mutationResolver{r} }

// Query returns QueryResolver implementation.
func (r *Resolver) Query() QueryResolver { return &queryResolver{r} }

type mutationResolver struct{ *Resolver }
type queryResolver struct{ *Resolver }

GetUser is pretty straight forward: it gets user id and returns the user from the hash map store.

CreateUser first checks if UserStore is initialized. Line 19. If CreateUser length is 0 it initializes the hash-map. Line 21.
Then it gets the values for username, id and userType from the input parameter and sets up the new user, stores it into the UserStore, line 29, and returns it.

 

Testing

Creating user

Mutation:

mutation createUserMutation($input: NewUser!) {
  createUser(input: $input) {
    name
    id
  }
}

Variables:

{
  "input": {
    "userId": "1",
    "userName": "John",
    "userType": "admin",
    "userGender": "male"
  }
}

Query for user with id

Query:

query getUserQuery($nid: ID!) {
  getUser(id:$nid) {
    id
    name
    userType
    userGender
  }
}

Variables:

{
  "nid": "1"
}

 

Zigzag Conversion

[tabby title=”Task”]

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);

Example 1:

Input:

 s = "PAYPALISHIRING", numRows = 3

Output:

 "PAHNAPLSIIGYIR"

Example 2:

Input:

 s = "PAYPALISHIRING", numRows = 4

Output:

 "PINALSIGYAHRPI"

Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I

Example 3:

Input:

 s = "A", numRows = 1

Output:

 "A"

 

This problem was taken from Leet code, ZigZag conversion

 

[tabby title=”Solution”]

It’s take the first example string: “PAYPALISHIRING

An array representation of the string would be done by pushing each character into the array.

Then if we want to iterate through this array in zig zag pattern with 3 rows, it will look like this:

 

Then, we have to create 3 arrays representing the 3 rows as follows:

Dots represent empty strings which we have to ignore before concatenating all 3 rows, convert them to string and this is the answer to this problem.

But how to create the loop to traverse through the zig zag pattern (figure 1) ?

  • first we set up `headingDown` flag to determine if we are going down or up
  • each time when the row reaches numRows we are flipping the value of headingDown
  • when headingDown is false (meaning that we are heading up) we have to do it diagonally: row — , col ++
  • when row become 0 we are flipping again headingDown and it becomes true again: row ++ and we keep storing values of every character we traversed in the result array.
 /**
 * @param {string} s
 * @param {number} numRows
 * @return {string}
 */
var convert = function(s, numRows) {

    // if we don't have any rows or there is an empty string just return back empty string
    if(s.length === 0 || numRows === 0) 
        return '';

    // if rows are numRows is just one, we return the same string
    if(numRows === 1) {
        return s;
    }
    
    var l = s.length;
    // put the string into single dimension array to iterate through
    var arr = s.split('');
    
    var rowsArray = [];
    var row = 0;
    var col = 0;
    var headingDown = true; // this determines if the cursor is heading down in the same column, or up leaping to the next column (dizgonal)

    // instantiate numRows arrays to store values of each row
    for(var i = 0; i < numRows; i ++) {
        rowsArray[i] = [];
    }

    // loop through each element in arr and fill rowsArray ()
    for(var i = 0; i < l; i ++) {
        rowsArray[row][col] = arr[i];
        if(headingDown) {
            row ++;
        }
        else {
            row --;
            col ++;
        }

        
        if(row == numRows -1) {
            headingDown = false;
        } else if(row == 0) {
            headingDown = true;
        }
        
    }

    // Read 2D array and assemble the string
    var result = [];
    for(var i = 0; i < numRows; i ++) {
        for(var j = 0; j < rowsArray[i].length; j ++) {
            if(typeof rowsArray[i][j] != 'undefined') {
                result.push(rowsArray[i][j]);
            }
        }
    }
    return result.join('');
};

convert('PAYPALISHIRING', 3);
convert('AB', 1);
//convert('ABC', 1);

 

How can we optimize this ?

the above example is good to read but not a good practical example. First we don’t need two dimensional array to store characters for each row. We could replace this with string array and just keep adding characters till we reached the end of the string. This way we also don’t need to keep track of cols

/**
 * @param {string} s
 * @param {number} numRows
 * @return {string}
 */
var convert = function(s, numRows) {

    // if we don't have any rows or there is an empty string just return back empty string
    if(s.length === 0 || numRows === 0) 
        return '';

    // if rows are numRows is just one, we return the same string
    if(numRows === 1) {
        return s;
    }
    
    var l = s.length;
    // put the string into single dimension array to iterate through
    var arr = s.split('');
    
    var left = 0;
    var arrStrings = [];
    var row = 0;
    var col = 0;
    var headingDown = true; // this determines if the cursor is heading down in the same column, or up leaping to the next column (dizgonal)

    // instantiate numRows arrays to store values of each row
    for(var i = 0; i < numRows; i ++) {
        arrStrings[i] = '';
    }

    
    // loop through each element in arr and fill arrStrings ()
    for(var i = 0; i < l; i ++) {
        //arrStrings[row][col] = arr[i];
        if(headingDown) {
            arrStrings[row] += arr[i];
            row ++;
        }
        else {
            arrStrings[row] += arr[i];
            row --;
            col ++;
        }

        
        if(row == numRows -1) {
            headingDown = false;
        } else if(row == 0) {
            headingDown = true;
        }
        
    }

    var result = '';
    // combine all strings and return as one 
    for(var i = 0; i < numRows; i ++) {
        result += arrStrings[i];
    }
        
    return result;
};

 

[tabbyending]

Log In With Apple using redirect pop-up

This tutorial demonstrates how to use oAuth to sign-in with Apple without using any library.We simply use HTTP GET request to their endpoint URL: appleid.apple.com/auth/authorize.

Just to space it up a bit, we are opening Sign-in popup in modal window using window.open but this could be done in the same window. The advantages of open it in modal window are that the user won’t be redirect to different screens and got confused of what’s going on.

Full example here

Main Web app

index.html

<html>
    <head>
      <style>

      </style>

    <script type = "text/javascript">

      var popUpObj;

      function showModalPopUp()    
      {
      popUpObj=window.open(
        "log-in-popup.html",
        "ModalPopUp",
        "toolbar=no," +
        "scrollbars=no," +
        "location=no," +
        "statusbar=no," +
        "menubar=no," +
        "resizable=0," +
        "width=500," +
        "height=640," +
        "left = 480," +
        "top=300"
      );

      popUpObj.focus();
      }   

      function receiveUserSignedInData(parsedToken) {
        console.dir(parsedToken, { depth: null });
      }

    </script>
    </head>
    <body>
    <h1>Welcome to oAuth example</h1>
    <input id="Button1" type="button" value="Log In" onclick="showModalPopUp()">
    </body>
</html>

The main app simply has a button that opens modal window with sign-in button. Line 39.

Log-In popup window

<html>
    <head>
        <style>
            #apple-auth-button {
                webkit-box-align: baseline;
                align-items: baseline;
                border-width: 0px;
                border-radius: 3px;
                box-sizing: border-box;
                display: inline-flex;
                font-size: inherit;
                font-style: normal;
                font-family: inherit;
                max-width: 100%;
                position: relative;
                text-align: center;
                text-decoration: none;
                transition: background 0.1s ease-out 0s, box-shadow 0.15s cubic-bezier(0.47, 0.03, 0.49, 1.38) 0s;
                white-space: nowrap;
                cursor: pointer;
                padding: 0px 10px;
                vertical-align: middle;
                width: 100%;
                -webkit-box-pack: center;
                justify-content: center;
                font-weight: bold;
                color: var(--ds-text,#42526E) !important;
                height: 40px !important;
                line-height: 40px !important;
                background: rgb(255, 255, 255) !important;
                box-shadow:  rgb(0 0 0 / 20%) 1px 1px 5px 0px !important           
            }
        </style>

    </head>
    <body>
        <a href="https://appleid.apple.com/auth/authorize?client_id=com.sign-in-with-apple-example-redirect-service&redirect_uri=https://www.toni-develops.com/external-files/examples/oauth-with-apple-with-redirect-step-by-step/callback.php&response_type=code id_token&state=123&scope=name email&response_mode=form_post">Sign In with Apple Simple A tag</a>

        <hr/>

        <div id="signInPanel">
            
            <form action="https://appleid.apple.com/auth/authorize?" method="get">
                <input type="hidden" id="client_id" name="client_id" value="com.sign-in-with-apple-example-redirect-service" />
                <input type="hidden" id="redirect_uri" name="redirect_uri" value="https://www.toni-develops.com/external-files/examples/oauth-with-apple-with-redirect-step-by-step/callback.php" />
                <input type="hidden" id="response_type" name="response_type" value="code id_token"/>
                <input type="hidden" id="scope" name="scope" value="name email" />
                <input type="hidden" id="response_mode" name="response_mode" value="form_post" />

                <button id="apple-auth-button" class="css-11s2kpt" type="submit" tabindex="0">
                <span class="css-1ujqpe8">
                    <img class="appleLogo" src="https://www.toni-develops.com/external-files/examples/assets/apple-logo.svg" alt="">
                </span>
                <span class="css-19r5em7"><span>Continue with Apple</span>
                </button> 
            </form>

          </div>        
    </body>
</html>

This window create two sign-in entities: one is simple A tag that demonstrates how we could start sign-in redirect process by simply redirect browser to authentication service, and the second one is a button, that does the same using form submit.

Callback function

callback.php

<html>
    <head>
      <style>

      </style>
      <script type = "text/javascript">
        var id_token = "<?php echo $_POST['id_token'] ?>";


        function parseJwt (token) {
          var base64Url = token.split('.')[1];
          var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
          var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) {
              return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
          }).join(''));

          return JSON.parse(jsonPayload);
        }           

        function sendDataToMainApp() {
          var parsedToken = parseJwt(id_token);
          window.opener.receiveUserSignedInData(parsedToken);
          window.close();
        }
      </script>
    </head>
    <body onLoad="sendDataToMainApp()">

    
    
    </body>
</html>

what we just did:

Were, we get id_token from Apple authentication service, that passes this via the request type that we selected (post, fragment, get) decodes, id_token then passes it to the parent window and closes itself.

 

Full example here