Browse Source

Add:
refreshToken
verifyUser
Fix:
Email Sender
Change:
getUserInfo

Sasan Torabkheslat 4 years ago
parent
commit
2e96be1a57
3 changed files with 97 additions and 16 deletions
  1. 76 9
      handler.go
  2. 8 2
      main.go
  3. 13 5
      token.go

+ 76 - 9
handler.go

@@ -101,7 +101,7 @@ func (h *handler) login(c echo.Context) error {
 	defer res.Body.Close()
 	//fmt.Println(res.StatusCode)
 	if res.StatusCode == 200 {
-		user := getUserInfo(cockie, username)
+		user := getUserInfo(token, username)
 		//fmt.Println(user.Result)
 		tokens, err := generateTokenPair(user, token)
 		if err != nil {
@@ -113,7 +113,8 @@ func (h *handler) login(c echo.Context) error {
 
 	return echo.ErrUnauthorized
 }
-func getUserInfo(cockie []*http.Cookie, username string) userInfo {
+func getUserInfo(token string, username string) userInfo {
+	fmt.Println("Checking for User: ", username)
 	url := URL + "/ipa/session/json"
 	method := "POST"
 	_json := fmt.Sprintf(`
@@ -145,7 +146,7 @@ func getUserInfo(cockie []*http.Cookie, username string) userInfo {
 	req.Header.Add("Referer", URL+"/ipa")
 	req.Header.Add("Content-Type", "application/json")
 	req.Header.Add("Accept", "text/plain")
-	req.Header.Add("Cookie", cockie[0].Raw)
+	req.Header.Add("Cookie", token)
 	res, err := client.Do(req)
 	defer res.Body.Close()
 	body, err := ioutil.ReadAll(res.Body)
@@ -213,7 +214,10 @@ func (h *handler) addUser(c echo.Context) error {
 	}
 	user := c.Get("user").(*jwt.Token)
 	claims := user.Claims.(jwt.MapClaims)
-	token := claims["IPAToken"].(string)
+	_sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
+	var hashChannel_ = make(chan []byte, 1)
+	hashChannel_ <- _sha256[:]
+	token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
 	b, err := json.Marshal(claims)
 	if err != nil {
 		fmt.Println("err:", err)
@@ -309,15 +313,18 @@ func (h *handler) addUser(c echo.Context) error {
 			return c.String(http.StatusBadRequest, "Error of error!!")
 		}
 		res2B, _ := json.Marshal(_apiErr)
-		return c.String(http.StatusBadRequest, "Failed with error \n"+string(res2B))
+		return c.String(http.StatusBadRequest, string(res2B))
 	}
-	sendMail("Welcome to ZiCloud\r\n Your temporary link is :\r\n https://zicloud.com/reset/"+url.QueryEscape(ciphertext), "Welcome to ZiCloud", mail)
-	return c.String(http.StatusOK, "Done, Pass:"+string(ciphertext))
+	go sendMail("Welcome to ZiCloud\r\n Your temporary link is :\r\n https://zicloud.com/reset/"+url.QueryEscape(ciphertext), "Welcome to ZiCloud", mail)
+	return c.String(http.StatusOK, "Done, Reset Link was sent to "+mail)
 }
 func (h *handler) disableUser(c echo.Context) error {
 	user := c.Get("user").(*jwt.Token)
 	claims := user.Claims.(jwt.MapClaims)
-	token := claims["IPAToken"].(string)
+	_sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
+	var hashChannel_ = make(chan []byte, 1)
+	hashChannel_ <- _sha256[:]
+	token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
 	username := c.FormValue("Username")
 	url := URL + "/ipa/session/json"
 	method := "POST"
@@ -444,7 +451,10 @@ func (h *handler) resetUser(c echo.Context) error {
 func (h *handler) dnsrecordadd(c echo.Context) error {
 	user := c.Get("user").(*jwt.Token)
 	claims := user.Claims.(jwt.MapClaims)
-	token := claims["IPAToken"].(string)
+	_sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
+	var hashChannel_ = make(chan []byte, 1)
+	hashChannel_ <- _sha256[:]
+	token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
 	recordName := c.FormValue("recordName")
 	record := c.FormValue("record")
 	url := URL + "/ipa/session/json"
@@ -492,3 +502,60 @@ func (h *handler) dnsrecordadd(c echo.Context) error {
 	defer res.Body.Close()
 	return c.String(http.StatusOK, "Done")
 }
+func (h *handler) token(c echo.Context) error {
+	user := c.Get("user").(*jwt.Token)
+	claims := user.Claims.(jwt.MapClaims)
+	_sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
+	var hashChannel_ = make(chan []byte, 1)
+	hashChannel_ <- _sha256[:]
+	token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
+	username := claims["name"].(string)
+	_user := getUserInfo(token, username)
+	//fmt.Println(user.Result)
+	newtokens, err := generateTokenPair(_user, token)
+	if err != nil {
+		return err
+	}
+	return c.JSON(http.StatusOK, newtokens)
+}
+func (h *handler) verifyUser(c echo.Context) error {
+	name := c.FormValue("Username")
+	fmt.Println("Name: ", name)
+	if name == "" {
+		return c.JSON(http.StatusNotFound, "User NOT Found")
+	}
+	username := "admin"
+	password := "h?_QJp5^&9FNc9w="
+	_url := URL + "/ipa/session/login_password"
+	method := "POST"
+	params := url.Values{}
+	params.Add("user", username)
+	params.Add("password", password)
+	payload := strings.NewReader(params.Encode())
+	tr := &http.Transport{
+		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
+	}
+	client := &http.Client{Transport: tr}
+	req, err := http.NewRequest(method, _url, payload)
+	audit("Recieved Login request from: " + RealIP)
+	if err != nil {
+		fmt.Println(err)
+	}
+	req.Header.Add("Referer", URL+"/ipa")
+	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
+	req.Header.Add("Accept", "text/plain")
+	res, err := client.Do(req)
+	cockie := res.Cookies()
+	token := cockie[0].Raw
+	defer res.Body.Close()
+	//fmt.Println(token)
+	if res.StatusCode == 200 {
+		user := getUserInfo(token, name)
+		if user.Result.Value != name {
+			return c.JSON(http.StatusNotFound, "User NOT Found")
+		}
+	}
+
+	return c.JSON(http.StatusOK, "User Founded")
+
+}

+ 8 - 2
main.go

@@ -7,6 +7,7 @@ import (
 	"encoding/base64"
 	"fmt"
 	"github.com/labstack/echo"
+	"github.com/labstack/echo/middleware"
 	"io"
 	"log"
 	"log/syslog"
@@ -40,7 +41,7 @@ func sendMail(str string, subject string, recipient string) {
 	rand.Read(buff)
 	random_str := base64.StdEncoding.EncodeToString(buff)
 	msg := []byte("To:" + recipient + "\r\n" +
-		"Date: " + time.Now().String() + "\r\n" +
+		"Date: " + time.Now().Format(time.RFC1123) + "\r\n" +
 		"Message-Id: <" + random_str + "@ZiCloud.com>" + "\r\n" +
 		"subject: " + subject + "\r\n" +
 		"From: ZiCloud <" + "zicloud@zi-tel.com" + ">\r\n" +
@@ -65,6 +66,10 @@ func main() {
 	}
 	echoHandler := echo.New()
 	echoHandler.Use(extractIP)
+	echoHandler.Use(middleware.CORSWithConfig(middleware.CORSConfig{
+		AllowOrigins: []string{"*", "*"},
+		AllowMethods: []string{http.MethodGet, http.MethodPost},
+	}))
 	audit("Application " + _appname + " (" + _appversion + ") Started by " + os.Getenv("USER"))
 	echoHandler.GET("/", func(c echo.Context) error {
 		return c.String(http.StatusOK, "Hello, World!")
@@ -79,8 +84,9 @@ func main() {
 	echoHandler.POST("/addUser", h.addUser, isLoggedIn, isAdmin)
 	echoHandler.POST("/disableUser", h.disableUser, isLoggedIn, isAdmin)
 	echoHandler.POST("/resetUser", h.resetUser)
+	echoHandler.GET("/verifyUser", h.verifyUser)
 	echoHandler.POST("/dnsrecordadd", h.dnsrecordadd, isLoggedIn, isAdmin)
-
+	echoHandler.POST("/token", h.token, isLoggedIn)
 	echoHandler.Logger.Fatal(echoHandler.Start(os.Args[1] + ":" + os.Args[2]))
 }
 func encrypt(key []byte, text string) string {

+ 13 - 5
token.go

@@ -1,6 +1,7 @@
 package main
 
 import (
+	"crypto/sha256"
 	"time"
 
 	"github.com/dgrijalva/jwt-go"
@@ -21,9 +22,13 @@ func generateTokenPair(user userInfo, cockieStr string) (map[string]string, erro
 		}
 	}
 	claims["sub"] = 1
-	claims["name"] = user.Result.Result.Displayname
-	claims["IPAToken"] = cockieStr
+	claims["name"] = user.Result.Result.Givenname[0]
+	sha256 := sha256.Sum256([]byte(user.Result.Result.Givenname[0]))
+	var hashChannel = make(chan []byte, 1)
+	hashChannel <- sha256[:]
+	claims["IPAToken"] = encrypt(<-hashChannel, cockieStr)
 	claims["memberof"] = user.Result.Result.MemberofGroup
+	claims["mail"] = user.Result.Result.Mail
 	claims["exp"] = time.Now().Add(time.Minute * 15).Unix()
 
 	// Generate encoded token and send it as response.
@@ -36,15 +41,18 @@ func generateTokenPair(user userInfo, cockieStr string) (map[string]string, erro
 	refreshToken := jwt.New(jwt.SigningMethodHS256)
 	rtClaims := refreshToken.Claims.(jwt.MapClaims)
 	rtClaims["sub"] = 1
+	rtClaims["IPAToken"] = claims["IPAToken"]
+	rtClaims["name"] = claims["name"]
+
 	rtClaims["exp"] = time.Now().Add(time.Hour * 24).Unix()
 
-	//rt, err := refreshToken.SignedString([]byte("secret"))
+	rt, err := refreshToken.SignedString([]byte("secret"))
 	if err != nil {
 		return nil, err
 	}
 
 	return map[string]string{
-		"access_token": t,
-		//"refresh_token": rt,
+		"access_token":  t,
+		"refresh_token": rt,
 	}, nil
 }