Skip to content

Commit

Permalink
Merge pull request #13 from natron-io/basic_implementation
Browse files Browse the repository at this point in the history
Basic implementation
  • Loading branch information
janlauber authored Jan 21, 2022
2 parents e521245 + 4805311 commit 0a5afa7
Show file tree
Hide file tree
Showing 9 changed files with 354 additions and 70 deletions.
1 change: 1 addition & 0 deletions CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* @natron-io/admins
17 changes: 15 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
# tenant-api
API to present data to the tenant-dashboard
API to present data to the tenant-dashboard with a GitHub oauth login.
Tenants represents the teams of a GitHub organization.

## api
`/github/login` - Login with GitHub \
`/api/v1/pods` - Get pods of a tenant \
`/api/v1/namespaces` - Get namespaces of a tenant \
`/api/v1/serviceaccounts` - Get serviceaccounts of a tenant by namespaces \
`/api/v1/cpurequests` - Get cpurequests of a tenant \
`/api/v1/memoryrequests` - Get memoryrequests of a tenant \
`/api/v1/storagerequests` - Get storagerequests of a tenant by storageclass \

`/api/v1/pods`
## env
`CLIENT_ID` - GitHub client id **required** \
`CLIENT_SECRET` - GitHub client secret **required** \
`SECRET_KEY` - JWT secret key *optional* (default: random 32 bytes, displayed in the logs) \
`LABELSELECTOR` - label key for selecting tenant ressources *optional* (default: "natron.io/tenant")

## local testing

Expand Down
84 changes: 68 additions & 16 deletions controllers/authController.go
Original file line number Diff line number Diff line change
@@ -1,52 +1,104 @@
package controllers

import (
"bytes"
"encoding/json"
"fmt"
"time"

"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt"
"github.com/natron-io/tenant-api/util"
)

var SECRET_KEY string

func GithubLogin(c *fiber.Ctx) error {
redirectURL := fmt.Sprintf("https://github.com/login/oauth/authorize?client_id=%s&redirect_uri=%s",
util.CLIENT_ID, "https://api.natron.io/login/github/callback")
redirectURL := fmt.Sprintf("https://github.com/login/oauth/authorize?scope=read:org&client_id=%s&redirect_uri=%s",
util.CLIENT_ID, "http://127.0.0.1:56668/login/github/callback") //api.natron.io

return c.Redirect(redirectURL)
}

func GithubCallback(c *fiber.Ctx) error {
// get code from "code" query param
code := c.Query("code")

// util.InfoLogger.Printf("Received code: %s", code)

githubAccessToken := util.GetGithubAccessToken(code)

githubData := util.GetGithubData(githubAccessToken)
// util.InfoLogger.Printf("Received access token: %s", githubAccessToken)

githubData := util.GetGithubTeams(githubAccessToken)

// util.InfoLogger.Printf("Received github data: %s", githubData)

return LoggedIn(c, githubData)
}

func LoggedIn(c *fiber.Ctx, githubData string) error {
if githubData != "" {
if githubData == "" {
// return unauthorized
return c.Status(401).JSON(fiber.Map{
"message": "Unauthorized",
})
}

// set response header to application/json
c.Set("Content-Type", "application/json")
// parse responsebody to map array
var githubDataMap []map[string]interface{}
json.Unmarshal([]byte(githubData), &githubDataMap)

// get each github team slug
var githubTeamSlugs []string
for _, githubTeam := range githubDataMap {
githubTeamSlugs = append(githubTeamSlugs, githubTeam["slug"].(string))
}

claims := jwt.MapClaims{
"github_team_slugs": githubTeamSlugs,
}

var prettyJSON bytes.Buffer
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, _ := token.SignedString([]byte(SECRET_KEY))

// Pretty-print the JSON
err := json.Indent(&prettyJSON, []byte(githubData), "", "\t")
if err != nil {
return c.Status(500).JSON(fiber.Map{
"message": "Internal Server Error",
})
cookie := &fiber.Cookie{
Name: "tenant-api-token",
Value: tokenString,
Expires: time.Now().Add(time.Hour * 24),
Path: "/",
}

c.Cookie(cookie)

return c.JSON(fiber.Map{
"message": "Logged in",
"data": githubTeamSlugs,
})

}

func CheckAuth(c *fiber.Ctx) []string {
cookie := c.Cookies("tenant-api-token")

if cookie == "" {
util.WarningLogger.Printf("IP %s is not authorized", c.IP())
return nil
}

token, _ := jwt.Parse(cookie, func(token *jwt.Token) (interface{}, error) {
_, ok := token.Method.(*jwt.SigningMethodHMAC)
if !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(SECRET_KEY), nil
})

claims := token.Claims.(jwt.MapClaims)

var githubTeamSlugs []string
for _, githubTeam := range claims["github_team_slugs"].([]interface{}) {
githubTeamSlugs = append(githubTeamSlugs, githubTeam.(string))
}

// Return the JSON
return c.JSON(prettyJSON.String())
return githubTeamSlugs
}
Loading

0 comments on commit 0a5afa7

Please sign in to comment.