Skip to content

Commit be4c8b8

Browse files
d
1 parent 89c6f79 commit be4c8b8

File tree

4 files changed

+77
-1
lines changed

4 files changed

+77
-1
lines changed

.account

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
ACCOUNT_NAME ACCOUNT_PASSWD

backend/internal/api/setup_router.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ func SetupRouter(cc *core.CoreController) *gin.Engine {
4343

4444
cc.GradeQueue <- gr
4545

46-
c.Header("Location", "/api/result/"+gr.Id)
46+
c.Header("Location", ApiPrefix+gr.Id)
4747
c.Status(202)
4848

4949
})

backend/internal/auth/auth.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package auth
2+
3+
import (
4+
"bufio"
5+
"errors"
6+
"io"
7+
"strings"
8+
"sync"
9+
)
10+
11+
type AuthController struct {
12+
accounts map[string]string
13+
lock sync.RWMutex
14+
}
15+
16+
func (ac *AuthController) Add(userName string, password string) {
17+
ac.lock.Lock()
18+
defer ac.lock.Unlock()
19+
20+
ac.accounts[userName] = password
21+
}
22+
23+
func (ac *AuthController) Auth(userName string, password string) bool {
24+
ac.lock.RLock()
25+
defer ac.lock.RUnlock()
26+
27+
psd, ok := ac.accounts[userName]
28+
return ok && psd == password
29+
}
30+
31+
func NewAuthController(accountInfo io.Reader) (*AuthController, error) {
32+
ret := AuthController{
33+
accounts: make(map[string]string),
34+
}
35+
scanner := bufio.NewScanner(accountInfo)
36+
37+
for {
38+
if !scanner.Scan() {
39+
break
40+
}
41+
text := scanner.Text()
42+
token := strings.Split(text, " ")
43+
if len(token) != 2 {
44+
return nil, errors.New("wrong format")
45+
}
46+
ret.Add(token[0], token[1])
47+
}
48+
49+
return &ret, nil
50+
51+
}

backend/internal/auth/auth_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package auth_test
2+
3+
import (
4+
"strings"
5+
"testing"
6+
7+
"github.com/markhuang1212/code-grader/backend/internal/auth"
8+
"github.com/stretchr/testify/assert"
9+
)
10+
11+
var authInfo string = `user1 123456
12+
user2 abcdef
13+
`
14+
15+
func TestAuth(t *testing.T) {
16+
info := strings.NewReader(authInfo)
17+
ac, err := auth.NewAuthController(info)
18+
assert.Nil(t, err)
19+
20+
assert.True(t, ac.Auth("user1", "123456"))
21+
assert.True(t, ac.Auth("user2", "abcdef"))
22+
23+
assert.False(t, ac.Auth("user2", "123456"))
24+
}

0 commit comments

Comments
 (0)