Skip to content

Commit

Permalink
Merge branch 'master' of https://github.com/2ne1ugly/Layton
Browse files Browse the repository at this point in the history
  • Loading branch information
2ne1ugly committed Feb 19, 2020
2 parents 85fdadc + 827479c commit 76682f1
Show file tree
Hide file tree
Showing 8 changed files with 395 additions and 0 deletions.
2 changes: 2 additions & 0 deletions build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/bin/bash
go build -o layton *.go
209 changes: 209 additions & 0 deletions identity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
package main

import (
"database/sql"
"encoding/json"
"net/http"

"github.com/gorilla/mux"
)

//
// createAccount
//
type createAccountRequest struct {
Username string `json:"username"`
}

type createAccountResponse struct {
ResultCode int64 `json:"resultCode"`
}

func createAccountHandler(w http.ResponseWriter, r *http.Request) {
LaytonLog("Handling create account")

//Read content
data, ok := ReadContent(r)
if !ok {
LaytonLog("Create Account Bad request")
return
}
LaytonLog(string(data))

//Parse to Json
var request createAccountRequest
err2 := json.Unmarshal(data, &request)
if err2 != nil {
LaytonLog(err2.Error())
return
}

//Setup Response and defer sending response
w.Header().Set("Content-Type", "application/json")
var response createAccountResponse
defer func() {
responseBlob, err := json.Marshal(response)
if err != nil {
LaytonLog("Create Account Failed to marshal")
w.WriteHeader(http.StatusInternalServerError)
return
}
LaytonLog(string(responseBlob))
w.Write(responseBlob)
}()

//Query if it already exists
queriedAccount := Account{}
err := db.Get(&queriedAccount, "SELECT * FROM accounts WHERE username=$1", request.Username)
if err != sql.ErrNoRows {
response.ResultCode = InternalError
if err != nil {
LaytonLog(err.Error())
}
return
}

//Try to insert it
_, err = db.Queryx("INSERT INTO layton.accounts (username) VALUES ($1)", request.Username)
if err != nil {
LaytonLog(err.Error())
response.ResultCode = InternalError
return
}

//send response
response.ResultCode = Ok
}

//
// login
//
type loginRequest struct {
Username string `json:"username"`
}

type loginResponse struct {
ResultCode int64 `json:"resultCode"`
AccessToken string `json:"accessToken"`
}

func loginHandler(w http.ResponseWriter, r *http.Request) {
LaytonLog("Handling Login")

//Read content
data, ok := ReadContent(r)
if !ok {
LaytonLog("Create Account Bad request")
return
}

//Parse to JSON
var request loginRequest
err2 := json.Unmarshal(data, &request)
if err2 != nil {
LaytonLog(err2.Error())
return
}

//Setup Response and defer sending response
w.Header().Set("Content-Type", "application/json")
var response loginResponse
defer func() {
responseBlob, err := json.Marshal(response)
if err != nil {
LaytonLog("login Failed to marshal")
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(responseBlob)
}()

//Query if it already exists

var queriedAccount Account
err := db.Get(&queriedAccount, "SELECT * FROM accounts WHERE username = $1", request.Username)
if err == sql.ErrNoRows {
LaytonLog("incorrect credentials")
response.ResultCode = IncorrectCredentials
return
} else if err != nil {
LaytonLog(err.Error())
response.ResultCode = InternalError
return
}

//Log into layton
if LogIntoLayton(&queriedAccount) {
response.ResultCode = Ok
response.AccessToken = queriedAccount.sessionToken
} else {
response.ResultCode = InternalError
LaytonLog("internal error")
}
}

//
// logout
//
type logoutRequest struct {
Username string `json:"username"`
}

type logoutResponse struct {
ResultCode int64 `json:"resultCode"`
}

func logoutHandler(w http.ResponseWriter, r *http.Request) {
LaytonLog("Handling Logout")

//Read content
data, ok := ReadContent(r)
if !ok {
LaytonLog("Create Account Bad request")
return
}

//Parse to JSON
var request logoutRequest
err2 := json.Unmarshal(data, &request)
if err2 != nil {
LaytonLog(err2.Error())
return
}

//Setup Response and defer sending response
w.Header().Set("Content-Type", "application/json")
var response logoutResponse
defer func() {
responseBlob, err := json.Marshal(response)
if err != nil {
LaytonLog("logout Failed to marshal")
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(responseBlob)
}()

//Query if it already exists
var queriedAccount Account
err := db.Get(&queriedAccount, "SELECT username FROM accounts WHERE username = $1", request.Username)
if err != nil {
LaytonLog("Logout Account does not exist")
response.ResultCode = DoesNotExist
return
}

//Log out layton
if LogOutFromLayton(queriedAccount) {
response.ResultCode = Ok
} else {
response.ResultCode = AlreadyLoggedOut
}
}

//BindIdentityHandlers Binds Identity related handles
func BindIdentityHandlers(r *mux.Router) {
r.HandleFunc("/Identity/CreateAccount", createAccountHandler)
r.HandleFunc("/Identity/Login", loginHandler)
r.HandleFunc("/Identity/Logout", logoutHandler)
}
Binary file added layton
Binary file not shown.
64 changes: 64 additions & 0 deletions layton.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
//
// Contains all necessary server information
//
package main

import (
"log"
"strconv"
)

//Account represents "RAM" version of account info.
type Account struct {
Username string `db:"username"`
sessionToken string
}

//LaytonServer is where data is stored in to run the server
type LaytonServer struct {
bInitialized bool
onlineAccounts map[string]Account //Key is username
}

var layton LaytonServer

//InitLayton initializes global variable layton
func InitLayton() {
layton.bInitialized = true
layton.onlineAccounts = make(map[string]Account)
}

//LogIntoLayton returns false for failure, true for success. Also modifies it so that it contains session token.
func LogIntoLayton(account *Account) bool {
if !layton.bInitialized {
log.Fatal("Layton Not Initialized")
}

//Check if account is logged in
_, ok := layton.onlineAccounts[account.Username]
if ok {
return false
}
account.sessionToken = account.Username + "_" + strconv.FormatInt(int64(len(layton.onlineAccounts)), 10)

//Add to onlineAccounts
layton.onlineAccounts[account.Username] = *account
return true
}

//LogOutFromLayton returns false for failure, true for success
func LogOutFromLayton(account Account) bool {
if !layton.bInitialized {
log.Fatal("Layton Not Initialized")
}

//Check if account is logged in
_, ok := layton.onlineAccounts[account.Username]
if !ok {
return false
}

//delete from onlineAccounts
delete(layton.onlineAccounts, account.Username)
return true
}
42 changes: 42 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package main

import (
"log"
"net/http"
"time"

"github.com/gorilla/mux"
_ "github.com/lib/pq"
)

func main() {
//Init SQL
LaytonLog("Setting up SQL")
CreateSQL()
defer DestroySQL()

//Bind functions
LaytonLog("Binding functions")
r := mux.NewRouter()
BindIdentityHandlers(r)

//Init Layton
InitLayton()

//Define server type
srv := &http.Server{
Handler: r,
Addr: "10.10.151.75:8000",

WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}

LaytonLog("Ready to serve")
//run server
err := srv.ListenAndServe()
if err != nil {
log.Fatalln(err)
}
return
}
1 change: 1 addition & 0 deletions pwd
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
user=layton dbname=postgres password=moobot sslmode=disable
33 changes: 33 additions & 0 deletions sql.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package main

import (
"io/ioutil"
"log"

"github.com/jmoiron/sqlx"
)

//DB : Global variable db interface, can handle concurrent goroutines
var db *sqlx.DB

//CreateSQL initializes database interface
func CreateSQL() {
data, _ := ioutil.ReadFile("pwd")

dbb, err := sqlx.Connect("postgres", string(data))
if err != nil {
log.Fatal(err)
}
// _, err = db.Query("USE layton")
// if err != nil {
// log.Fatal(err)
// }
db = dbb
}

//DestroySQL destorys database interface
func DestroySQL() {
db.Close()

db = nil
}
Loading

0 comments on commit 76682f1

Please sign in to comment.