1
0
mirror of https://github.com/muety/wakapi.git synced 2023-08-10 21:12:56 +03:00

Minor code cleanup.

This commit is contained in:
Ferdinand Mütsch 2019-11-07 23:11:19 +01:00
parent 121b8c9885
commit fe1cc3ac88
7 changed files with 21 additions and 21 deletions

18
main.go
View File

@ -105,11 +105,11 @@ func main() {
migrateLanguages(db, config)
// Services
aliasSrvc := &services.AliasService{config, db}
heartbeatSrvc := &services.HeartbeatService{config, db}
userSrvc := &services.UserService{config, db}
summarySrvc := &services.SummaryService{config, db, heartbeatSrvc, aliasSrvc}
aggregationSrvc := &services.AggregationService{config, db, userSrvc, summarySrvc, heartbeatSrvc}
aliasSrvc := &services.AliasService{Config: config, Db: db}
heartbeatSrvc := &services.HeartbeatService{Config: config, Db: db}
userSrvc := &services.UserService{Config: config, Db: db}
summarySrvc := &services.SummaryService{Config: config, Db: db, HeartbeatService: heartbeatSrvc, AliasService: aliasSrvc}
aggregationSrvc := &services.AggregationService{Config: config, Db: db, UserService: userSrvc, SummaryService: summarySrvc, HeartbeatService: heartbeatSrvc}
// Aggregate heartbeats to summaries and persist them
go aggregationSrvc.Schedule()
@ -119,8 +119,8 @@ func main() {
summaryHandler := &routes.SummaryHandler{SummarySrvc: summarySrvc}
// Middlewares
authenticate := &middlewares.AuthenticateMiddleware{UserSrvc: userSrvc}
cors := cors.New(cors.Options{
authenticateMiddleware := &middlewares.AuthenticateMiddleware{UserSrvc: userSrvc}
corsMiddleware := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedHeaders: []string{"*"},
Debug: false,
@ -139,9 +139,9 @@ func main() {
// Sub-Routes Setup
router.PathPrefix("/api").Handler(negroni.Classic().
With(cors).
With(corsMiddleware).
With(
negroni.HandlerFunc(authenticate.Handle),
negroni.HandlerFunc(authenticateMiddleware.Handle),
negroni.Wrap(apiRouter),
))
router.PathPrefix("/").Handler(negroni.Classic().With(negroni.Wrap(http.FileServer(http.Dir("./static")))))

View File

@ -37,10 +37,10 @@ func (m *AuthenticateMiddleware) Handle(w http.ResponseWriter, r *http.Request,
var user *models.User
var userKey string
user, userKey, err := m.tryGetUserByApiKey(r)
user, userKey, err := m.tryGetUserByPassword(r)
if err != nil {
user, userKey, err = m.tryGetUserByPassword(r)
user, userKey, err = m.tryGetUserByApiKey(r)
}
if err != nil {
@ -57,7 +57,7 @@ func (m *AuthenticateMiddleware) Handle(w http.ResponseWriter, r *http.Request,
func (m *AuthenticateMiddleware) tryGetUserByApiKey(r *http.Request) (*models.User, string, error) {
authHeader := strings.Split(r.Header.Get("Authorization"), " ")
if len(authHeader) != 2 || authHeader[0] != "Basic" {
return nil, "", errors.New("Failed to extract API key")
return nil, "", errors.New("failed to extract API key")
}
key, err := base64.StdEncoding.DecodeString(authHeader[1])
@ -82,7 +82,7 @@ func (m *AuthenticateMiddleware) tryGetUserByApiKey(r *http.Request) (*models.Us
func (m *AuthenticateMiddleware) tryGetUserByPassword(r *http.Request) (*models.User, string, error) {
authHeader := strings.Split(r.Header.Get("Authorization"), " ")
if len(authHeader) != 2 || authHeader[0] != "Basic" {
return nil, "", errors.New("Failed to extract API key")
return nil, "", errors.New("failed to extract API key")
}
hash, err := base64.StdEncoding.DecodeString(authHeader[1])
@ -97,7 +97,7 @@ func (m *AuthenticateMiddleware) tryGetUserByPassword(r *http.Request) (*models.
re := regexp.MustCompile(`^(.+):(.+)$`)
groups := re.FindAllStringSubmatch(userKey, -1)
if len(groups) == 0 || len(groups[0]) != 3 {
return nil, "", errors.New("Failed to parse user agent string")
return nil, "", errors.New("failed to parse user agent string")
}
userId, password := groups[0][1], groups[0][2]
user, err = m.UserSrvc.GetUserById(userId)
@ -107,7 +107,7 @@ func (m *AuthenticateMiddleware) tryGetUserByPassword(r *http.Request) (*models.
passwordHash := md5.Sum([]byte(password))
passwordHashString := hex.EncodeToString(passwordHash[:])
if passwordHashString != user.Password {
return nil, "", errors.New("Invalid password")
return nil, "", errors.New("invalid password")
}
} else {
user = cachedUser.(*models.User)

View File

@ -69,7 +69,7 @@ func (j *HeartbeatReqTime) Scan(value interface{}) error {
*j = HeartbeatReqTime(value.(time.Time))
break
default:
return errors.New("Unsupported type")
return errors.New("unsupported type")
}
return nil
}

View File

@ -62,13 +62,13 @@ func (h *SummaryHandler) Get(w http.ResponseWriter, r *http.Request) {
from = utils.StartOfYear()
default:
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Missing 'from' parameter"))
w.Write([]byte("missing 'from' parameter"))
return
}
}
live := (params.Get("live") != "" && params.Get("live") != "false") || interval == IntervalToday
recompute := (params.Get("recompute") != "" && params.Get("recompute") != "false")
recompute := params.Get("recompute") != "" && params.Get("recompute") != "false"
to := utils.StartOfDay()
if live {
to = time.Now()

View File

@ -36,7 +36,7 @@ func (srv *AliasService) GetAliasOrDefault(userId string, summaryType uint8, val
}
return value, nil
}
return "", errors.New("User aliases not initialized")
return "", errors.New("user aliases not initialized")
}
func (src *AliasService) IsInitialized(userId string) bool {

View File

@ -188,7 +188,7 @@ func (srv *SummaryService) aggregateBy(heartbeats []*models.Heartbeat, summaryTy
func getMissingIntervals(from, to time.Time, existingSummaries []*models.Summary) []*Interval {
if len(existingSummaries) == 0 {
return []*Interval{&Interval{from, to}}
return []*Interval{{from, to}}
}
intervals := make([]*Interval, 0)

View File

@ -22,7 +22,7 @@ func ParseUserAgent(ua string) (string, string, error) {
re := regexp.MustCompile(`^wakatime\/[\d+.]+\s\((\w+).*\)\s.+\s(\w+)\/.+$`)
groups := re.FindAllStringSubmatch(ua, -1)
if len(groups) == 0 || len(groups[0]) != 3 {
return "", "", errors.New("Failed to parse user agent string")
return "", "", errors.New("failed to parse user agent string")
}
return groups[0][1], groups[0][2], nil
}