first commit

This commit is contained in:
Bryan Joshua Pedini 2020-09-15 09:48:54 +02:00
commit 58c8f54a9a
4 changed files with 93 additions and 0 deletions

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module git.bjphoster.com/bryanpedini/go-totp
go 1.14

47
main.go Normal file
View File

@ -0,0 +1,47 @@
package main
import (
"fmt"
"encoding/json"
"net/http"
"strings"
"text/template"
"time"
"github.com/xlzd/gotp"
)
type secret struct {
S string `json:"secret"`
}
type code struct {
C string `json:"code"`
T int `json:"time"`
}
func calculate(w http.ResponseWriter, r *http.Request) {
var s secret
json.NewDecoder(r.Body).Decode(&s)
totp := gotp.NewDefaultTOTP(s.S).Now()
c := &code{
C: totp,
T: int(30 - time.Now().Unix()%30),
}
response, _ := json.Marshal(c)
w.Header().Set("Content-Type", "application/json")
w.Write(response)
}
func index(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("templates/index.html")
t.Execute(w, nil)
}
func main() {
staticFolder := http.FileServer(http.Dir("./static"))
http.HandleFunc("/", index)
http.HandleFunc("/calculate", calculate)
http.Handle("/static/", http.StripPrefix(strings.TrimRight("/static/", "/"), staticFolder))
fmt.Println("Listening on 127.0.0.1:8000")
http.ListenAndServe("127.0.0.1:8000", nil)
}

22
static/main.js Normal file
View File

@ -0,0 +1,22 @@
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function update() {
var d = new Date()
console.log(d.getMilliseconds())
}
function send() {
var secret = document.getElementsByClassName("secretBox")[0].value;
var xhr = new XMLHttpRequest();
xhr.open("POST", "/calculate", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
secret: secret,
}));
xhr.onload = function() {
document.getElementsByClassName("totp-response-code")[0].innerHTML = JSON.parse(this.responseText)["code"];
document.getElementsByClassName("totp-response-time")[0].innerHTML = JSON.parse(this.responseText)["time"];
}
}

21
templates/index.html Normal file
View File

@ -0,0 +1,21 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="author" content="Bryan Pedini">
<title id="page-title">TOTP Web Generator</title>
</head>
<body>
<input class="secretBox" type="text" placeholder="secret">
<button class="btn btn-secondary" onclick="send()"><i class="fas fa-key"></i> Get your code</button>
<div class="totp-response">
<span>Your code: <span class="totp-response-code"></span></span><br>
<span>Remaining time: <span class="totp-response-time"></span></span>
</div>
<script src="/static/main.js"></script>
</body>
</html>