Skip to content

Commit

Permalink
Add #193 Align APIs to GovStack: Change URL paths for onboard endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
albinpa committed Oct 4, 2023
1 parent ae4b7ff commit 03becee
Show file tree
Hide file tree
Showing 15 changed files with 872 additions and 1 deletion.
2 changes: 1 addition & 1 deletion resources/config
27 changes: 27 additions & 0 deletions src/handlerv2/getorganizationbyid_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package handlerv2

import (
"encoding/json"
"fmt"
"net/http"

"github.com/bb-consent/api/src/common"
"github.com/bb-consent/api/src/config"
"github.com/bb-consent/api/src/org"
)

// GetOrganizationByID Gets a single organization by given id
func GetOrganizationByID(w http.ResponseWriter, r *http.Request) {
organizationID := r.Header.Get(config.OrganizationId)
o, err := org.Get(organizationID)

if err != nil {
m := fmt.Sprintf("Failed to get organization by ID :%v", organizationID)
common.HandleError(w, http.StatusNotFound, m, err)
return
}

w.Header().Set(config.ContentTypeHeader, config.ContentTypeJSON)
response, _ := json.Marshal(organization{o})
w.Write(response)
}
28 changes: 28 additions & 0 deletions src/handlerv2/getorganizationimage_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package handlerv2

import (
"fmt"
"net/http"

"github.com/bb-consent/api/src/common"
"github.com/bb-consent/api/src/config"
"github.com/bb-consent/api/src/image"
"github.com/gorilla/mux"
)

// GetOrganizationImage Retrieves the organization image
func GetOrganizationImage(w http.ResponseWriter, r *http.Request) {
organizationID := r.Header.Get(config.OrganizationId)
imageID := mux.Vars(r)["imageID"]

image, err := image.Get(imageID)

if err != nil {
m := fmt.Sprintf("Failed to fetch image with id: %v for org: %v", imageID, organizationID)
common.HandleError(w, http.StatusInternalServerError, m, err)
return
}

w.Header().Set(config.ContentTypeHeader, config.ContentTypeImage)
w.Write(image.Data)
}
74 changes: 74 additions & 0 deletions src/handlerv2/gettoken_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package handlerv2

import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"

"github.com/asaskevich/govalidator"
"github.com/bb-consent/api/src/common"
"github.com/bb-consent/api/src/config"
)

type tokenReq struct {
RefreshToken string `valid:"required"`
ClientID string `valid:"required"`
}

// GetToken return access token when refresh token is given
func GetToken(w http.ResponseWriter, r *http.Request) {
var tReq tokenReq
b, _ := ioutil.ReadAll(r.Body)
defer r.Body.Close()
json.Unmarshal(b, &tReq)

// validating request payload for refreshing tokens
valid, err := govalidator.ValidateStruct(tReq)

if !valid {
log.Printf("Failed to refresh token")
common.HandleError(w, http.StatusBadRequest, err.Error(), err)
return
}

data := url.Values{}
data.Set("refresh_token", tReq.RefreshToken)
data.Add("client_id", tReq.ClientID)
data.Add("grant_type", "refresh_token")

resp, err := http.PostForm(iamConfig.URL+"/realms/"+iamConfig.Realm+"/protocol/openid-connect/token", data)
if err != nil {
//m := fmt.Sprintf("Failed to get token from refresh token for user:%v", token.GetUserName(r))
m := fmt.Sprintf("Failed to get token from refresh token")
common.HandleError(w, http.StatusInternalServerError, m, err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
//m := fmt.Sprintf("Failed to get token from refresh token user:%v", token.GetUserName(r))
m := fmt.Sprintf("Failed to get token from refresh token")
common.HandleError(w, http.StatusInternalServerError, m, err)
return
}

if resp.StatusCode != http.StatusOK {
var e iamError
json.Unmarshal(body, &e)
response, _ := json.Marshal(e)
w.WriteHeader(resp.StatusCode)
w.Header().Set(config.ContentTypeHeader, config.ContentTypeJSON)
w.Write(response)
return
}

var tok iamToken
json.Unmarshal(body, &tok)
response, _ := json.Marshal(tok)
w.WriteHeader(resp.StatusCode)
w.Header().Set(config.ContentTypeHeader, config.ContentTypeJSON)
w.Write(response)
}
87 changes: 87 additions & 0 deletions src/handlerv2/loginadminuser_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package handlerv2

import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"

"github.com/asaskevich/govalidator"
"github.com/bb-consent/api/src/actionlog"
"github.com/bb-consent/api/src/common"
"github.com/bb-consent/api/src/config"
"github.com/bb-consent/api/src/token"
"github.com/bb-consent/api/src/user"
)

type loginReq struct {
Username string `valid:"required,email"`
Password string `valid:"required"`
}

type loginResp struct {
User user.User
Token iamToken
}

// LoginAdminUser Implements the admin users login
func LoginAdminUser(w http.ResponseWriter, r *http.Request) {
var lReq loginReq
b, _ := ioutil.ReadAll(r.Body)
defer r.Body.Close()
json.Unmarshal(b, &lReq)

log.Printf("Login username: %v", lReq.Username)

// validating the request payload
valid, err := govalidator.ValidateStruct(lReq)

if !valid {
log.Printf("Invalid request params for authentication")
common.HandleError(w, http.StatusBadRequest, err.Error(), err)
return
}

t, status, iamErr, err := getToken(lReq.Username, lReq.Password, "igrant-ios-app", iamConfig.Realm)
if err != nil {
if (iamError{}) != iamErr {
resp, _ := json.Marshal(iamErr)
w.WriteHeader(status)
w.Header().Set(config.ContentTypeHeader, config.ContentTypeJSON)
w.Write(resp)
return
}
m := fmt.Sprintf("Failed to get token for user:%v", lReq.Username)
common.HandleError(w, status, m, err)
return
}
accessToken, err := token.ParseToken(t.AccessToken)
if err != nil {
m := fmt.Sprintf("Failed to parse token for user:%v", lReq.Username)
common.HandleError(w, status, m, err)
return
}

u, err := user.GetByIamID(accessToken.IamID)
if err != nil {
m := fmt.Sprintf("User: %v does not exist", lReq.Username)
common.HandleError(w, http.StatusUnauthorized, m, err)
return
}

if len(u.Roles) == 0 {
//Normal user can not login with this API.
m := fmt.Sprintf("Non Admin User: %v tried admin login", lReq.Username)
common.HandleError(w, http.StatusForbidden, m, err)
return
}

actionLog := fmt.Sprintf("%v logged in", u.Email)
actionlog.LogOrgSecurityCalls(u.ID.Hex(), u.Email, u.Roles[0].OrgID, actionLog)
lResp := loginResp{u, t}
resp, _ := json.Marshal(lResp)
w.WriteHeader(http.StatusOK)
w.Header().Set(config.ContentTypeHeader, config.ContentTypeJSON)
w.Write(resp)
}
69 changes: 69 additions & 0 deletions src/handlerv2/loginuser_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package handlerv2

import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"

"github.com/asaskevich/govalidator"
"github.com/bb-consent/api/src/common"
"github.com/bb-consent/api/src/config"
"github.com/bb-consent/api/src/user"
)

// LoginUser Implements the user login
func LoginUser(w http.ResponseWriter, r *http.Request) {
var lReq loginReq

b, _ := ioutil.ReadAll(r.Body)
defer r.Body.Close()

json.Unmarshal(b, &lReq)

log.Printf("Login username: %v", lReq.Username)

// validating the request payload
valid, err := govalidator.ValidateStruct(lReq)

if !valid {
log.Printf("Invalid request params for authentication")
common.HandleError(w, http.StatusBadRequest, err.Error(), err)
return
}

t, status, iamErr, err := getToken(lReq.Username, lReq.Password, "igrant-ios-app", iamConfig.Realm)
if err != nil {
if (iamError{}) != iamErr {
resp, _ := json.Marshal(iamErr)
w.WriteHeader(status)
w.Header().Set(config.ContentTypeHeader, config.ContentTypeJSON)
w.Write(resp)
return
}
m := fmt.Sprintf("Failed to get token for user:%v", lReq.Username)
common.HandleError(w, status, m, err)
return
}
sanitizedUserName := common.Sanitize(lReq.Username)

//TODO: Remove me when the auth server is per dev environment
u, err := user.GetByEmail(sanitizedUserName)
if err != nil {
m := fmt.Sprintf("Login failed for non existant user:%v", lReq.Username)
common.HandleError(w, http.StatusUnauthorized, m, err)
return
}

if len(u.Roles) > 0 {
m := fmt.Sprintf("Login not allowed for admin users:%v", lReq.Username)
common.HandleError(w, http.StatusUnauthorized, m, err)
return
}

resp, _ := json.Marshal(t)
w.WriteHeader(http.StatusOK)
w.Header().Set(config.ContentTypeHeader, config.ContentTypeJSON)
w.Write(resp)
}
64 changes: 64 additions & 0 deletions src/handlerv2/updateorganization_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package handlerv2

import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"

"github.com/bb-consent/api/src/common"
"github.com/bb-consent/api/src/config"
"github.com/bb-consent/api/src/org"
"github.com/bb-consent/api/src/user"
)

type orgUpdateReq struct {
Name string
Location string
Description string
PolicyURL string
}

// UpdateOrganization Updates an organization
func UpdateOrganization(w http.ResponseWriter, r *http.Request) {
var orgUpReq orgUpdateReq
b, _ := ioutil.ReadAll(r.Body)
defer r.Body.Close()

json.Unmarshal(b, &orgUpReq)

organizationID := r.Header.Get(config.OrganizationId)

o, err := org.Get(organizationID)
if err != nil {
m := fmt.Sprintf("Failed to get organization: %v", organizationID)
common.HandleError(w, http.StatusInternalServerError, m, err)
return
}

if strings.TrimSpace(orgUpReq.Name) != "" {
o.Name = orgUpReq.Name
}
if strings.TrimSpace(orgUpReq.Location) != "" {
o.Location = orgUpReq.Location
}
if strings.TrimSpace(orgUpReq.Description) != "" {
o.Description = orgUpReq.Description
}
if strings.TrimSpace(orgUpReq.PolicyURL) != "" {
o.PolicyURL = orgUpReq.PolicyURL
}

orgResp, err := org.Update(o)
if err != nil {
m := fmt.Sprintf("Failed to update organization: %v", organizationID)
common.HandleError(w, http.StatusInternalServerError, m, err)
return
}
go user.UpdateOrganizationsSubscribedUsers(orgResp)
//response, _ := json.Marshal(organization{orgResp})
//w.Header().Set(config.ContentTypeHeader, config.ContentTypeJSON)
w.WriteHeader(http.StatusAccepted)
//w.Write(response)
}
Loading

0 comments on commit 03becee

Please sign in to comment.