Gologin is Golang (Go) login manager working with RDBMS Databases

Overview

What is Gologin

Gologin is an easy to setup professional login manager for Go web applications. It helps you protect your application resources from unattended, unauthenticated or unauthorized access. Currently it works with SQL databases authentication. It is flexible, you can use it with any user/roles table structure in database.

How to setup

Get the package with following command :

go get github.com/birddevelper/gologin

How to use

You can easily setup and customize login process with configure() function. You should specify following paramters to make the Gologin ready to start:

  • Login page : path to html template. Default path is ./template/login.html, note that the template must be defined as "login" with {{define "login"}} at the begining line

  • Login path : login http path. Default path is /login

  • Session timeout : Number of seconds before the session expires. Default value is 120 seconds.

  • SQL connection, and SQL query to authenticate user and fetch roles : 2 SQL queries to retrieve user and its roles by given username and password. The authentication query must return only single arbitary column, it must have a where clause with two placeholder ::username and ::password. And the query for retrieving user's roles must return only the text column of role name.

  • Wrap desired endpoints to protect : You should wrap the endpoints you want to protect with gologin.LoginRequired or gologin.RolesRequired function in the main function.( see the example)

gologin.LoginRequired requires user to be authenticated for accessing the wrapped endpoint/page.

gologin.RolesRequired requires user to have specified roles in addition to be authenticated.

See the example :

package main

import (
	"database/sql"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/birddevelper/gologin"
	_ "github.com/go-sql-driver/mysql"
)

// static assets like CSS and JavaScript
func public() http.Handler {
	return http.StripPrefix("/static/", http.FileServer(http.Dir("./static")))
}

// a page in our application, it needs user only be authenticated
func securedPage() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hi! Welcome to secured page.")
	})
}

// another page in our application, it needs user be authenticated and have ADMIN role
func securedPage2() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hi! Welcome to very secured page.")
	})
}


func main() {
	// create connection to database
	db, err := sql.Open("mysql", "root:[email protected](127.0.0.1:6666)/mydb")
	if err != nil {
		log.Fatal(err)
	}

	// Gologin configuration
	gologin.Configure().
		SetLoginPage("./template/login.html"). // set login page html template path
		SetSessionTimeout(90).                 // set session expiration time in seconds
		SetLoginPath("/login").                // set login http path
		// set database connection and sql query
		AuthenticateBySqlQuery(
			db,
			"select id from users where username = ::username and password = ::password", // authentication query
			"select role from user_roles where userid = (select id from users where username = ::username)") // fetch user's roles

	// instantiate http server
	mux := http.NewServeMux()

	mux.Handle("/static/", public())

	// use Gologin login handler for /login endpoint
	mux.Handle("/login", gologin.LoginHandler())

	// use Gologin logout handler for /logout endpoint
	mux.Handle("/logout", gologin.LogoutHandler())

	// the pages/endpoints that we need to protect should be wrapped with gologin.LoginRequired
	mux.Handle("/mySecuredPage", gologin.LoginRequired(securedPage()))

	mux.Handle("/mySecuredPage2", gologin.RolesRequired(securedPage2()),"ADMIN")

	// server configuration
	addr := ":8080"
	server := http.Server{
		Addr:         addr,
		Handler:      mux,
		ReadTimeout:  15 * time.Second,
		WriteTimeout: 15 * time.Second,
		IdleTimeout:  15 * time.Second,
	}

	// start listening to network
	if err := server.ListenAndServe(); err != nil {
		log.Fatalf("main: couldn't start simple server: %v\n", err)
	}
}

It is mandatory to set the login form's username input as "username" and password input as "password". Note that the form must send form data as post to the same url (set no action attribute).

Html template for login page :

{{define "login"}}
<html>
    <body>
        <H2>
            Login Page
        </H2>
        <form method="post">
            <!-- username input with "username" name -->
            <input type="text" name="username" />
            <input type="password" name="password" />
            <input type="submit" value="Login" />
        </form>
    </body>
</html>

{{end}}

You can also store data in in-memory session storage in any type during user's session with SetSession function, and retrieve it back by GetSession function.

func securedPage2() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// get the session data, the request parameter is *http.Request
		age, err : = gologin.GetSession("age", request)

		// as the GetSession returns type is interface{}, we should specify the exact type of the session entry
		fmt.Printf("Your age is " + age.(int))
	})
}

GetDataReturnedByAuthQuery function returns the data of the column you specified in authentication SQL query. And with GetCurrentUsername you can get the current user's username.

func securedPage2() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// get the current user's username, the request parameter is *http.Request
			username : = gologin.GetCurrentUsername(request)

			fmt.Printf("Welcome " + username)
	})
}

Todo list

  • mongoDB support
Releases(v1.1.2)
Owner
Bird
Developer
Bird
Modular Kubernetes operator to manage the lifecycle of databases

Ensemble Ensemble is a simple and modular Kubernetes Operator to manage the lifecycle of a wide range of databases. Infrastructure as code with Kubern

Tesera 42 Mar 1, 2022
Kubegres is a Kubernetes operator allowing to create a cluster of PostgreSql instances and manage databases replication, failover and backup.

Kubegres is a Kubernetes operator allowing to deploy a cluster of PostgreSql pods with data replication enabled out-of-the box. It brings simplicity w

Reactive Tech Ltd 989 May 9, 2022
The Oracle Database Operator for Kubernetes (a.k.a. OraOperator) helps developers, DBAs, DevOps and GitOps teams reduce the time and complexity of deploying and managing Oracle Databases

The Oracle Database Operator for Kubernetes (a.k.a. OraOperator) helps developers, DBAs, DevOps and GitOps teams reduce the time and complexity of deploying and managing Oracle Databases. It eliminates the dependency on a human operator or administrator for the majority of database operations.

Oracle 64 May 12, 2022
library for working with github api, written in Golang

gitdata library for working with github api, written in Golang Example: get user data package main import ( "fmt" "log" "github.com/a1excoder/git

Aleksandr Rudenko 0 Jan 1, 2022
A golang package for comparing and working with k0s version numbers

version A go-language package for managing k0s version numbers. It is based on hashicorp/go-version but adds sorting and comparison capabilities for t

k0s - The Zero Friction Kubernetes by Team Lens 0 Feb 7, 2022
MenuStart plugin to nwg-panel, also capable of working standalone

nwg-menu This code provides the MenuStart plugin to nwg-panel. It also may be used standalone, however, with a little help from command line arguments

Piotr Miller 25 May 2, 2022
Working towards a control plane for the MiCo Tool and the MiCoProxy

A simple control plane for MiCo This is still largely a work in progress The overall idea is to build a kubernetes DaemonSet that watches kubernetes s

null 0 May 4, 2022
Additional Terraform resources for working with AWS KMS

This is a (hopefully temporary) Terraform provider for working with AWS KMS, particularly for generating data keys. It attempts to correct a deficienc

CipherStash 0 Nov 29, 2021
Automated-gke-cilium-networkpolicy-demo - Quickly provision and tear down a GKE cluster with Cilium enabled for working with Network Policy.

Automated GKE Network Policy Demo Before running the automation, make sure you have the correct variables in env-automation/group_vars/all.yaml. There

Casey Wylie 0 Jan 1, 2022
A library containing useful functions for working with Go types.

Go Type Tools A library containing useful functions for working with Go types. Table of Contents Reasoning Examples Array Map Int String Usage License

eloonstra 6 Feb 18, 2022
A Golang package for simplifying storing configuration in the OS-provided secret manager.

go-keyconfig A Golang package for simplifying storing configuration in the OS-provided secret manager. Operating System Support OS Secret Manager MacO

Joe Garcia 13 Feb 7, 2022
The missing package manager for golang binaries (its homebrew for "go install")

Bingo: The missing package manager for golang binaries (its homebrew for "go install") Do you love the simplicity of being able to download & compile

TekWizely 175 Apr 29, 2022
Go Version Manager

gvm By Josh Bussdieker (jbuss, jaja, jbussdieker) while working at Moovweb Currently lovingly maintained by Benjamin Knigge Pull requests and other an

Moovweb 7.3k May 12, 2022
A simple and powerful SSH keys manager

SKM is a simple and powerful SSH Keys Manager. It helps you to manage your multiple SSH keys easily! Features Create, List, Delete your SSH key(s) Man

Timothy 770 May 9, 2022
Go version manager. Super simple tool to install and manage Go versions. Install go without root. Gobrew doesn't require shell rehash.

gobrew Go version manager Install or update With curl $ curl -sLk https://git.io/gobrew | sh - or with go $ go get -u github.com/kevincobain2000/gobre

Pulkit Kathuria 99 Apr 29, 2022
Kubernetes Lazy User Manager

klum - Kubernetes Lazy User Manager klum does the following basic tasks: Create/Delete/Modify users Easily manage roles associated with users Issues k

Darren Shepherd 273 Apr 18, 2022
network-node-manager is a kubernetes controller that controls the network configuration of a node to resolve network issues of kubernetes.

Network Node Manager network-node-manager is a kubernetes controller that controls the network configuration of a node to resolve network issues of ku

kakao 95 May 9, 2022
The smart virtual machines manager. A modern CLI for Vagrant Boxes.

The smart virtual machines manager Table of Contents: What is Vermin Install Vermin Usage Contributors TODO What is Vermin Vermin is a smart, simple a

Muhammad Hewedy 124 May 9, 2022