feat/interactive-auth #9

Merged
Joren merged 2 commits from feat/interactive-auth into main 2026-06-19 21:19:59 +02:00
5 changed files with 89 additions and 32 deletions
Showing only changes of commit 07fade16d3 - Show all commits

View File

@@ -31,15 +31,11 @@ go build -o canvasarchiver ./cmd/canvasarchiver
./canvasarchiver -vo
```
Or to use a manually generated Canvas API token:
```bash
./canvasarchiver --api
```
2. On first run, you'll be prompted to choose an authentication method:
- **[1] Login via browser (OAuth)**: Visit the provided URL, authorize, and paste the code
- **[2] Use Canvas API token**: Enter a manually generated API token (e.g. `12230~...`)
2. On first run, you'll be prompted to authenticate:
- Visit the provided OAuth URL
- Authorize the application
- Copy the authorization code back to the terminal
The choice is saved and reused on subsequent runs.
3. Enter your Course ID when prompted (or use `-me` to download all enrolled courses)
@@ -58,8 +54,6 @@ go build -o canvasarchiver ./cmd/canvasarchiver
| `-vo` | Videos only — scan recordings and all module video items, download everything flat into one directory; skips regular files |
| `-me` | Download all enrolled courses |
| `-n` | Prefix modules with order numbers `[1]`, `[2]`, etc. |
| `--api` | Use a manually generated Canvas API token instead of OAuth |
## Configuration
@@ -72,9 +66,7 @@ The following constants can be modified in `internal/config/config.go`:
## Authentication
Credentials are stored in `credentials.json` after the first successful login. The refresh token is automatically used for subsequent runs.
With `--api`, enter a manually generated Canvas API token on first use. It is saved to `credentials.json` and reused on later `--api` runs.
Credentials are stored in `credentials.json` after the first successful authentication. The chosen method is remembered for subsequent runs — OAuth refresh tokens are automatically refreshed, and API tokens are validated before saving.
## Notes

View File

@@ -17,19 +17,12 @@ func main() {
videosOnly := flag.Bool("vo", false, "Videos only mode - download only Panopto videos to a single directory")
me := flag.Bool("me", false, "Download all enrolled courses")
moduleNumbers := flag.Bool("n", false, "Prefix modules with order numbers [1], [2], etc.")
apiToken := flag.Bool("api", false, "Use a manually generated Canvas API token instead of OAuth")
flag.Parse()
httpClient := &http.Client{}
authenticator := auth.NewAuthenticator(httpClient)
var accessToken string
var err error
if *apiToken {
accessToken, err = authenticator.GetAPIToken()
} else {
accessToken, err = authenticator.GetAccessToken()
}
accessToken, err := authenticator.GetToken()
if err != nil {
fmt.Printf("Authentication failed: %v\n", err)
return

View File

@@ -27,7 +27,32 @@ func NewAuthenticator(client *http.Client) *Authenticator {
}
}
func (a *Authenticator) GetAccessToken() (string, error) {
func (a *Authenticator) GetToken() (string, error) {
creds, err := LoadCredentials()
if err == nil && creds.AuthMethod != "" {
switch creds.AuthMethod {
case "api":
token := strings.TrimSpace(creds.APIToken)
if token == "" {
return a.promptMethod()
}
fmt.Print("[*] Validating saved API token... ")
if err := a.validateAPIToken(token); err != nil {
fmt.Println("FAILED")
fmt.Printf("[!] %v\n", err)
SaveCredentials(&models.Credentials{})
return a.promptMethod()
}
fmt.Println("OK")
return token, nil
case "oauth":
return a.refreshOrLogin()
}
}
return a.promptMethod()
}
func (a *Authenticator) refreshOrLogin() (string, error) {
creds, err := LoadCredentials()
if err != nil {
return a.login()
@@ -52,36 +77,66 @@ func (a *Authenticator) GetAccessToken() (string, error) {
return tr.AccessToken, nil
}
func (a *Authenticator) GetAPIToken() (string, error) {
creds, err := LoadCredentials()
if err == nil && strings.TrimSpace(creds.APIToken) != "" {
fmt.Println("[*] Reusing saved API token...")
return strings.TrimSpace(creds.APIToken), nil
func (a *Authenticator) promptMethod() (string, error) {
fmt.Println("Select authentication method:")
fmt.Println(" [1] Login via browser (OAuth)")
fmt.Println(" [2] Use Canvas API token")
fmt.Print("Choice (1/2): ")
input, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil && err != io.EOF {
return "", err
}
if err != nil {
creds = &models.Credentials{}
switch strings.TrimSpace(input) {
case "2":
return a.setupAPIToken()
default:
return a.login()
}
}
func (a *Authenticator) setupAPIToken() (string, error) {
fmt.Print("Enter Canvas API token: ")
token, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil && err != io.EOF {
return "", err
}
token = strings.TrimSpace(token)
if token == "" {
return "", fmt.Errorf("empty API token")
}
creds.APIToken = token
if err := SaveCredentials(creds); err != nil {
fmt.Print("[*] Validating API token... ")
if err := a.validateAPIToken(token); err != nil {
fmt.Println("FAILED")
return "", err
}
fmt.Println("OK")
if err := SaveCredentials(&models.Credentials{
AuthMethod: "api",
APIToken: token,
}); err != nil {
return "", err
}
fmt.Println("[+] API token saved.")
return token, nil
}
func (a *Authenticator) validateAPIToken(token string) error {
req, _ := http.NewRequest("GET", config.BaseURL+"/api/v1/users/self", nil)
req.Header.Set("Authorization", "Bearer "+token)
resp, err := a.HTTPClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("invalid token: %d %s", resp.StatusCode, strings.TrimSpace(string(body)))
}
return nil
}
func (a *Authenticator) login() (string, error) {
codeVerifier, codeChallenge, err := generatePKCEPair()
if err != nil {
@@ -211,6 +266,7 @@ func SaveRefreshToken(refreshToken string) error {
creds = &models.Credentials{}
}
creds.RefreshToken = refreshToken
creds.AuthMethod = "oauth"
return SaveCredentials(creds)
}

View File

@@ -16,6 +16,13 @@ import (
"git.directme.in/Joren/CanvasArchiver/internal/utils"
)
func checkAPIResponse(resp *http.Response) error {
if resp.StatusCode < 300 {
return nil
}
return fmt.Errorf("API error: %d", resp.StatusCode)
}
type Client struct {
HTTPClient *http.Client
AccessToken string
@@ -48,6 +55,10 @@ func (c *Client) GetCourseInfo() error {
}
defer resp.Body.Close()
if err := checkAPIResponse(resp); err != nil {
return err
}
var course models.Course
json.NewDecoder(resp.Body).Decode(&course)
@@ -64,6 +75,10 @@ func (c *Client) GetEnrolledCourses() ([]models.Course, error) {
}
defer resp.Body.Close()
if err := checkAPIResponse(resp); err != nil {
return nil, err
}
var courses []models.Course
json.NewDecoder(resp.Body).Decode(&courses)
return courses, nil

View File

@@ -1,6 +1,7 @@
package models
type Credentials struct {
AuthMethod string `json:"auth_method,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
APIToken string `json:"api_token,omitempty"`
}