-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add support for Moodle Course Completion Webhooks #4
Draft
ATechAdventurer
wants to merge
9
commits into
main
Choose a base branch
from
support/moodle
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+170
−2
Draft
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
f5406ac
Add moodle Secrets
ATechAdventurer f1740c2
Add moodle webhook handler
ATechAdventurer 94288b5
Added GetUserByEmail and AddUserToGroup
ATechAdventurer 9eabcda
Update moodle/moodle.go
ATechAdventurer 91b69c8
Merge branch 'main' of https://github.com/TheLab-ms/profile into supp…
ATechAdventurer 7a30f17
Use default HTTP Client
ATechAdventurer 4a09e96
Rename Moodle.Moodle to Moodle.Client
ATechAdventurer 2be7e99
Cleanup
ATechAdventurer 3f2f37b
Fix the Unlink Account button (#7)
ATechAdventurer File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -22,6 +22,7 @@ import ( | |
|
||
"github.com/TheLab-ms/profile/conf" | ||
"github.com/TheLab-ms/profile/keycloak" | ||
"github.com/TheLab-ms/profile/moodle" | ||
"github.com/TheLab-ms/profile/stripeutil" | ||
) | ||
|
||
|
@@ -50,6 +51,7 @@ func main() { | |
stripe.Key = env.StripeKey | ||
|
||
kc := keycloak.New(env) | ||
m := moodle.New(env) | ||
priceCache := stripeutil.StartPriceCache() | ||
|
||
// Redirect from / to /profile | ||
|
@@ -71,6 +73,7 @@ func main() { | |
// Webhooks | ||
http.HandleFunc("/webhooks/docuseal", newDocusealWebhookHandler(kc)) | ||
http.HandleFunc("/webhooks/stripe", newStripeWebhookHandler(env, kc)) | ||
http.HandleFunc("/webhooks/moodle", newMoodleWebhookHandler(env, kc, m)) | ||
|
||
// Embed (into the compiled binary) and serve any files from the assets directory | ||
http.Handle("/assets/", http.FileServer(http.FS(assets))) | ||
|
@@ -306,6 +309,58 @@ func newStripeWebhookHandler(env *conf.Env, kc *keycloak.Keycloak) http.HandlerF | |
} | ||
} | ||
|
||
func newMoodleWebhookHandler(env *conf.Env, kc *keycloak.Keycloak, m *moodle.Client) http.HandlerFunc { | ||
return func(w http.ResponseWriter, r *http.Request) { | ||
body := struct { | ||
EventName string `json:"eventname"` | ||
Host string `json:"host"` | ||
Token string `json:"token"` | ||
CourseID string `json:"courseid"` | ||
UserID string `json:"relateduserid"` | ||
}{} | ||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil { | ||
log.Printf("invalid json sent to moodle webhook endpoint: %s", err) | ||
w.WriteHeader(400) | ||
return | ||
} | ||
if body.Token != env.MoodleSecret { | ||
log.Printf("invalid moodle webhook secret") | ||
w.WriteHeader(400) | ||
return | ||
} | ||
switch body.EventName { | ||
case "\\core\\event\\course_completed": | ||
log.Printf("got moodle course completion submission webhook") | ||
|
||
// Lookup user by moodle ID to get email address | ||
moodleUser, err := m.GetUserByID(body.UserID) | ||
if err != nil { | ||
log.Printf("error while looking up user by moodle ID: %s", err) | ||
w.WriteHeader(500) | ||
return | ||
} | ||
// Use email address to lookup user in Keycloak | ||
user, err := kc.GetUserByEmail(r.Context(), moodleUser.Email) | ||
if err != nil { | ||
log.Printf("error while looking up user by email: %s", err) | ||
w.WriteHeader(500) | ||
return | ||
} | ||
|
||
err = kc.AddUserToGroup(r.Context(), user.ID, "6e413212-c1d8-4bc9-abb3-51944ca35327") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Consider exposing the group ID as an env var in case it ever changes |
||
if err != nil { | ||
log.Printf("error while adding user to group: %s", err) | ||
w.WriteHeader(500) | ||
return | ||
} | ||
|
||
default: | ||
log.Printf("unhandled moodle webhook event type: %s, ignoring", body.EventName) | ||
} | ||
|
||
} | ||
} | ||
|
||
// getUserID allows the oauth2proxy header to be overridden for testing. | ||
func getUserID(r *http.Request) string { | ||
user := r.Header.Get("X-Forwarded-Preferred-Username") | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
package moodle | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
"io" | ||
"net/http" | ||
|
||
"github.com/TheLab-ms/profile/conf" | ||
) | ||
|
||
type Client struct { | ||
url string | ||
token string | ||
} | ||
|
||
type User struct { | ||
ID int `json:"id"` | ||
UserName string `json:"username"` | ||
FirstName string `json:"firstname"` | ||
LastName string `json:"lastname"` | ||
FullName string `json:"fullname"` | ||
Email string `json:"email"` | ||
Suspended bool `json:"suspended"` | ||
Confirmed bool `json:"confirmed"` | ||
ProfileImageURL string `json:"profileimageurl"` | ||
} | ||
|
||
func New(c *conf.Env) *Client { | ||
return &Client{url: c.MoodleURL, token: c.MoodleWSToken} | ||
} | ||
|
||
func (m *Client) GetUserByID(id string) (*User, error) { | ||
url := fmt.Sprintf("%s/webservice/rest/server.php?wstoken=%s&wsfunction=core_user_get_users_by_field&field=id&values[0]=%s&moodlewsrestformat=json", m.url, m.token, id) | ||
|
||
client := http.DefaultClient | ||
req, err := http.NewRequest("GET", url, nil) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
res, err := client.Do(req) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
defer res.Body.Close() | ||
|
||
if res.StatusCode != http.StatusOK { | ||
body, _ := io.ReadAll(res.Body) | ||
return nil, fmt.Errorf("received non-OK HTTP status %d: %s", res.StatusCode, body) | ||
} | ||
|
||
var users []User // Declare users as a slice of User | ||
if err := json.NewDecoder(res.Body).Decode(&users); err != nil { | ||
return nil, err | ||
} | ||
|
||
if len(users) == 0 { | ||
return nil, fmt.Errorf("no user found with ID %s", id) | ||
} | ||
|
||
return &users[0], nil // Return the first user in the array | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not necessary in this PR, but it would be nice to move the
gocloak.User
->User
conversion logic into a helper function to avoid duplication.