Skip to content

Commit

Permalink
fix login
Browse files Browse the repository at this point in the history
  • Loading branch information
storm committed Oct 22, 2017
1 parent a528d4a commit d24340f
Show file tree
Hide file tree
Showing 7 changed files with 181 additions and 34 deletions.
2 changes: 2 additions & 0 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,15 @@ func main() {

router.ServeFiles("/public/*filepath", http.Dir("public/"))
router.GET("/", mw.LoggingMiddleware(mw.AuthCheck(indexHandler)))
router.GET("/index", mw.LoggingMiddleware(mw.AuthCheck(indexHandler)))

userObj.SetRouter(router)

s := http.Server{
Addr : ":8082",
Handler : router,
}

fmt.Printf("Server running at port %s\n", s.Addr)
s.ListenAndServe()

Expand Down
2 changes: 1 addition & 1 deletion config/config.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"user" : "gosec",
"password" : "gosec321",
"dbname" :"gosec",
"dbname" :"govwa",
"sqlhost" : "192.168.56.101",
"sqlport" : "3306",
"webserver" : "http://localhost",
Expand Down
10 changes: 7 additions & 3 deletions templates/template.login.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{{define "template.login"}}
<!DOCTYPE html>
<html>

<head>
<title>{{.Title}}</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
Expand All @@ -19,13 +19,14 @@
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">GOVWA User Login</h3>
<h3 class="panel-title" style="text-align:center">GoVWA User Login</h3>
</div>
<div class="panel-body">
{{.message}}
<form action="" role="form" method="post" accept-charset="utf-8">
<fieldset>
<div class="form-group">
<input type="text" name="identity" value="" class="form-control" placeholder="username" />
<input type="text" name="username" value="" class="form-control" placeholder="username" />
</div>
<div class="form-group">
<input type="password" name="password" value="" class="form-control" placeholder="Password" />
Expand All @@ -40,6 +41,9 @@ <h3 class="panel-title">GOVWA User Login</h3>
</div>
</body>
<script>
$(document).ready(function(){
$("#message").delay(2000).fadeOut();
});
</script>

</html>
Expand Down
6 changes: 3 additions & 3 deletions templates/template.sidebar.html
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@
</li>

<li data-toggle="collapse" data-target="#csrf" class="collapsed">
<a href="#"><i class="fa fa-bug fa-lg"></i> CSRF <span class="arrow"></span></a>
<a href="#"><i class="fa fa-bug fa-lg"></i> XXE <span class="arrow"></span></a>
</li>
<ul class="sub-menu collapse" id="csrf">
<li><a href="#">CSRF 1</a></li>
<li><a href="#">CSRF 2</a></li>
<li><a href="#">XXE 1</a></li>
<li><a href="#">XXE 2</a></li>
</ul>
</ul>
</div>
Expand Down
71 changes: 52 additions & 19 deletions user/session/session.go
Original file line number Diff line number Diff line change
@@ -1,53 +1,86 @@
package session

import(
"net/http"
"fmt"
import (
"log"
"govwa/util"
"net/http"

"github.com/gorilla/sessions"
)

type Self struct{}

func New()*Self{
func New() *Self {
return &Self{}
}

var store = sessions.NewCookieStore([]byte(util.Cfg.Sessionkey))

func (self *Self)SetSession(w http.ResponseWriter, r *http.Request, data map[string]string){
func (self *Self) SetSession(w http.ResponseWriter, r *http.Request, data map[string]string) {
session, err := store.Get(r, "govwa")


if err != nil {
log.Println(err.Error())
}

session.Options = &sessions.Options{
Path: "/",
MaxAge: 86400,
HttpOnly:true,
}

if err != nil{
fmt.Println(err.Error());
HttpOnly: true,
}

session.Values["govwa_session"] = true

err = session.Save(r,w) //safe session and send it to client as cookie
err = session.Save(r, w) //safe session and send it to client as cookie

if err != nil {
log.Println(err.Error())
}

//create new session to store on server side
if data != nil{
for key, value := range data {
session.Values[key] = value
}
}

}

func (self *Self) GetSession(r *http.Request, key string) interface{} {
session, err := store.Get(r, "govwa")

if err != nil {
log.Println(err.Error())
return nil
}
return session.Values[key]
}

for key,value := range data{
session.Values[key] = value
func (self *Self) DeleteSession(w http.ResponseWriter, r *http.Request) {
session, err := store.Get(r, "govwa")
if err != nil {
log.Println(err.Error())
}

if err != nil{
fmt.Println(err.Error())
session.Options = &sessions.Options{
Path: "/",
MaxAge: -1,
HttpOnly: true,
}
session.Values["govwa_session"] = true
err = session.Save(r, w) //safe session and send it to client as cookie

if err != nil {
log.Println(err.Error())
}

return
}

func (self *Self) IsLoggedIn(r *http.Request)bool{
func (self *Self) IsLoggedIn(r *http.Request) bool {
s, err := store.Get(r, "govwa")
if err != nil{
fmt.Println(err.Error())
if err != nil {
log.Println(err.Error())
}
if auth, ok := s.Values["govwa_session"].(bool); !ok || !auth {
return false
Expand Down
113 changes: 105 additions & 8 deletions user/user.go
Original file line number Diff line number Diff line change
@@ -1,24 +1,121 @@

package user

import(
"govwa/util"
import (
"log"
"fmt"
"net/http"
"crypto/md5"
"encoding/hex"
"html/template"
"database/sql"

"govwa/util"
"govwa/user/session"
"govwa/util/middleware"
"govwa/util/database"

"github.com/julienschmidt/httprouter"
)

type Self struct{}
/*
uname : admin
pass : govwaadmin
uname : user1
pass : govwauser1
*/

type Self struct{} //oop like syntax

func New()*Self{
func New() *Self {
return &Self{}
}
func (self *Self)SetRouter(r *httprouter.Router){
r.GET("/login", LoginViewHandler)
func (self *Self) SetRouter(r *httprouter.Router) {
/* register all router */

mw := middleware.New() //implement middleware

r.GET("/login", mw.LoggingMiddleware(LoginViewHandler))
r.POST("/login", mw.LoggingMiddleware(LoginViewHandler))
r.GET("/logout", mw.LoggingMiddleware(Logout))
}

func LoginViewHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params){
func LoginViewHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {

/* handler for login view */

/* value of data will send to client over template */
data := make(map[string]interface{})
data["Title"] = "Login"
data["govwahost"] = util.Fullurl

s := session.New()

if s.IsLoggedIn(r) { //if user session isset wkwk redirect to index page
util.Redirect(w, r, "index", 302)
}

if r.Method == "POST" {
if loginAction(w, r, ps){
util.Redirect(w, r, "index", 302)
}else{
//the best solution instead of using ajax request
data["message"] = template.HTML("<div id=\"message\" class=\"alert alert-danger\"><p>Incorrect Username or Password</p></div>")
log.Println("Login Failed")
}
}
util.SafeRender(w, "template.login", data)
}

func loginAction(w http.ResponseWriter, r *http.Request, _ httprouter.Params) bool{

/* handler for login action */
uname := r.FormValue("username")
pass := Md5Sum(r.FormValue("password"))
if checkUserQuery(uname, pass) == 1 {
s := session.New()
s.SetSession(w, r, nil)
log.Println("Login Success")
return true
} else {
return false
}
}

func Logout(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
s := session.New()
s.DeleteSession(w, r)
util.Redirect(w, r, "login", 302)
}

var db *sql.DB
func checkUserQuery(username,pass string)int{
/* this function will check rows num which return from query */
db, err := database.Connect()
if err != nil{
log.Println(err.Error())
}

var count int

sql := fmt.Sprintf(`SELECT COUNT(*)
FROM Users
WHERE uname=?
AND pass=?`)

stmt,err := db.Prepare(sql)
if err != nil{
fmt.Println(err.Error())
}
defer stmt.Close()
err = stmt.QueryRow(username,pass).Scan(&count)
return count

}

func Md5Sum(text string) string {
hasher := md5.New()
hasher.Write([]byte(text))
return hex.EncodeToString(hasher.Sum(nil))
}
11 changes: 11 additions & 0 deletions util/http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package util

import (
"fmt"
"net/http"
)

func Redirect(w http.ResponseWriter, r *http.Request, location string, code int){
redirect := fmt.Sprintf("%s%s", Fullurl,location)
http.Redirect(w,r,redirect,code)
}

0 comments on commit d24340f

Please sign in to comment.