In this Golang Web Development Series #10, we will learn the on how to use protect Golang HTTP Server CSRF by using this Gorilla CSRF package with step by step guide here in Golang's Web Development Series.
Get Linode Account:
https://www.linode.com/?r=6aae17162e9...
Maharlikans Code Github:
https://github.com/maharlikanscode/go...
#MaharlikansCode
#GolangWebDevelopment10
#GolangCSRF
#GolangHTTPServerCSRF
#GolangTutorial
#LearnGolangWebDevelopment
#Golang
#LifeAsSoftwareDeveloper
#Maharlikans
#FilipinoSoftwareDeveloper
If you go with extra mile for buying me a cup of coffee, I appreciate it guys: https://ko-fi.com/maharlikanscode
Source Codes:
package api
import (
"encoding/json"
"fmt"
"gowebapp/config"
"io/ioutil"
"net/http"
"strconv"
"strings"
"github.com/gorilla/mux"
"github.com/itrepablik/itrlog"
"github.com/itrepablik/tago"
)
// AuthRouters are the collection of all URLs for the Auth App.
func AuthRouters(r *mux.Router) {
r.HandleFunc("/api/v1/user/login", LoginUserEndpoint).Methods("POST")
}
// LoginUserEndpoint is to validate the user's login credential
func LoginUserEndpoint(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
w.WriteHeader(http.StatusOK)
body, errBody := ioutil.ReadAll(r.Body)
if errBody != nil {
itrlog.Error(errBody)
panic(errBody.Error())
}
keyVal := make(map[string]string)
json.Unmarshal(body, &keyVal)
userName := strings.TrimSpace(keyVal["username"])
password := keyVal["password"]
isSiteKeepMe, _ := strconv.ParseBool(keyVal["isSiteKeepMe"])
fmt.Print("userName: ", userName)
fmt.Print("password: ", password)
fmt.Print("isSiteKeepMe: ", isSiteKeepMe)
// Check if username is empty
if len(strings.TrimSpace(userName)) == 0 {
w.Write([]byte(`{ "isSuccess": "false", "alertTitle": "Username is Required BK", "alertMsg": "Please enter your username.", "alertType": "error" }`))
return
}
// Check if password is empty
if len(strings.TrimSpace(password)) == 0 {
w.Write([]byte(`{ "isSuccess": "false", "alertTitle": "Password is Required BK", "alertMsg": "Please enter your password.", "alertType": "error" }`))
return
}
expDays := "1" // default to expire in 1 day.
if isSiteKeepMe == true {
expDays = config.UserCookieExp
}
encryptedUserName, err := tago.Encrypt(userName, config.MyEncryptDecryptSK)
if err != nil {
itrlog.Error(err)
}
w.Write([]byte(`{ "isSuccess": "true", "alertTitle": "Login Successful", "alertMsg": "Your account has been verified and it's successfully logged-in.",
"alertType": "success", "redirectTo": "` + config.SiteBaseURL + `dashboard", "eUsr": "` + encryptedUserName + `", "expDays": "` + expDays + `" }`))
}
ajax post:
function loginForm()
{
//Get the form instance
username = $("#username").val();
password = $("#password").val();
isSiteKeepMe = $('#isSiteKeepMe').is(':checked');
if (csrfToken === undefined || csrfToken === null || csrfToken ===""){
Swal.fire("CSRF Token is Missing!", "Please try to refresh your page to get the new csrf token, if not, please report this to us instead. Thank you!", "error");
return false;
}
if (username === undefined || username === null || username ===""){
Swal.fire("Username is Required!", "Please enter your username!", "error");
$("#username").focus();
return false;
}
if (password === undefined || password === null || password ===""){
Swal.fire("Password is Required!", "Please enter your password", "error");
$("#password").focus();
return false;
}
var obj = { username: username, password: password, isSiteKeepMe: new String(isSiteKeepMe) };
var data = JSON.stringify(obj);
$.ajax({
method: "POST",
headers: {
'X-CSRF-TOKEN':csrfToken,
'Content-Type':'application/json'
},
url: BASE_URL+'api/v1/user/login',
data: data,
cache: false,
dataType: "json",
beforeSend: function(){
//Start displaying button's working animation
var loadingText = 'signing in...';
if ($("#btnLogin").html() !== loadingText) {
$("#btnLogin").data('original-text', $("#btnLogin").html());
$("#btnLogin").html(loadingText);
}
},
success: function(response)
{
$("#btnLogin").html($("#btnLogin").data('original-text')); //stop animation and switch back to original text
if (response.isSuccess === "false") {
Swal.fire(response.alertTitle, response.alertMsg, response.alertType);
}else{
Swal.fire(response.alertTitle, response.alertMsg, response.alertType);
}
}
});