Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 17 additions & 17 deletions server/src/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,8 @@ func (c MainController) corsAllowGetMiddleware(h http.Handler) http.Handler {
func router() (*mux.Router, *sqlx.DB) {
db := model.NewDB(config.DBDataSource())
userRepo := persistence.NewUserRepository(db)
main := MainController{db: db, userRepo: userRepo}
activistRepo := persistence.NewActivistRepository(db)
main := MainController{db: db, userRepo: userRepo, activistRepo: activistRepo}
csrfMiddleware := csrf.Protect(
[]byte(config.CsrfAuthKey),
csrf.Secure(config.IsProd), // disable secure flag in dev
Expand Down Expand Up @@ -282,6 +283,7 @@ func router() (*mux.Router, *sqlx.DB) {

// Authed API
router.Handle("/api/csrf-token", csrfMiddleware(alice.New(main.apiAttendanceAuthMiddleware).ThenFunc(main.CSRFTokenHandler))).Methods(http.MethodGet)
router.Handle("/api/activists", alice.New(main.apiOrganizerOrNonSFBayAuthMiddleware).ThenFunc(main.ActivistsSearchHandler)).Methods(http.MethodGet)
router.Handle("/activist_names/get", alice.New(main.apiAttendanceAuthMiddleware).ThenFunc(main.AutocompleteActivistsHandler))
router.Handle("/activist_names/get_organizers", alice.New(main.apiAttendanceAuthMiddleware).ThenFunc(main.AutocompleteOrganizersHandler))
router.Handle("/activist_names/get_chaptermembers", alice.New(main.apiAttendanceAuthMiddleware).ThenFunc(main.AutocompleteChapterMembersHandler))
Expand Down Expand Up @@ -356,8 +358,9 @@ func router() (*mux.Router, *sqlx.DB) {
}

type MainController struct {
db *sqlx.DB
userRepo model.UserRepository
db *sqlx.DB
userRepo model.UserRepository
activistRepo model.ActivistRepository
}

func (c MainController) authRoleMiddleware(h http.Handler, allowedRoles []string) http.Handler {
Expand All @@ -378,7 +381,7 @@ func (c MainController) authRoleMiddleware(h http.Handler, allowedRoles []string
return
}

if !userIsAllowed(allowedRoles, user) {
if !model.UserHasAnyRole(allowedRoles, user) {
http.Redirect(w, r.WithContext(setUserContext(r, user)), "/403", http.StatusFound)
return
}
Expand All @@ -404,18 +407,6 @@ func (c MainController) authAdminMiddleware(h http.Handler) http.Handler {
return c.authRoleMiddleware(h, []string{"admin"})
}

func userIsAllowed(roles []string, user model.ADBUser) bool {
for i := 0; i < len(roles); i++ {
for _, r := range user.Roles {
if r == roles[i] {
return true
}
}
}

return false
}

func getUserMainRole(user model.ADBUser) string {
if len(user.Roles) == 0 {
return ""
Expand Down Expand Up @@ -454,7 +445,7 @@ func (c MainController) apiRoleMiddleware(h http.Handler, allowedRoles []string)
return
}

if !userIsAllowed(allowedRoles, user) {
if !model.UserHasAnyRole(allowedRoles, user) {
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}
Expand Down Expand Up @@ -1692,6 +1683,15 @@ func (c MainController) CSRFTokenHandler(w http.ResponseWriter, r *http.Request)
})
}

func (c MainController) ActivistsSearchHandler(w http.ResponseWriter, r *http.Request) {
authedUser, authed := c.getAuthedADBUser(r)
if !authed {
panic("ActivistsSearchHandler requires authed ADB user")
}

transport.ActivistsSearchHandler(w, r, authedUser, c.activistRepo)
}

func (c MainController) UsersListHandler(w http.ResponseWriter, r *http.Request) {
transport.UsersListHandler(w, r, c.userRepo)
}
Expand Down
233 changes: 161 additions & 72 deletions server/src/model/activist.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"io"
"log"
"slices"

"regexp"
"strconv"
Expand Down Expand Up @@ -388,9 +389,10 @@ type ActivistEventData struct {
}

type ActivistMembershipData struct {
ActivistLevel string `db:"activist_level"`
Source string `db:"source"`
Hiatus bool `db:"hiatus"`
ActivistLevel string `db:"activist_level"`
DateOrganizer sql.NullTime `db:"date_organizer"`
Source string `db:"source"`
Hiatus bool `db:"hiatus"`
}

type ActivistConnectionData struct {
Expand Down Expand Up @@ -445,72 +447,72 @@ type ActivistExtra struct {
}

type ActivistJSON struct {
Email string `json:"email"`
Facebook string `json:"facebook"`
ID int `json:"id"`
Location string `json:"location"`
Name string `json:"name"`
PreferredName string `json:"preferred_name"`
Phone string `json:"phone"`
Pronouns string `json:"pronouns"`
Language string `json:"language"`
Accessibility string `json:"accessibility"`
Birthday string `json:"dob"`
ChapterID int `json:"chapter_id"`

FirstEvent string `json:"first_event"`
LastEvent string `json:"last_event"`
FirstEventName string `json:"first_event_name"`
LastEventName string `json:"last_event_name"`
LastAction string `json:"last_action"`
MonthsSinceLastAction int `json:"months_since_last_action"`
TotalEvents int `json:"total_events"`
TotalPoints int `json:"total_points"`
Active bool `json:"active"`
Status string `json:"status"`

ActivistLevel string `json:"activist_level"`
Source string `json:"source"`
Hiatus bool `json:"hiatus"`

Connector string `json:"connector"`
Training0 string `json:"training0"`
Training1 string `json:"training1"`
Training4 string `json:"training4"`
Training5 string `json:"training5"`
Training6 string `json:"training6"`
ConsentQuiz string `json:"consent_quiz"`
TrainingProtest string `json:"training_protest"`
ApplicationDate string `json:"dev_application_date"`
ApplicationType string `json:"dev_application_type"`
Quiz string `json:"dev_quiz"`
DevInterest string `json:"dev_interest"`

CMFirstEmail string `json:"cm_first_email"`
CMApprovalEmail string `json:"cm_approval_email"`
ProspectOrganizer bool `json:"prospect_organizer"`
ProspectChapterMember bool `json:"prospect_chapter_member"`
LastConnection string `json:"last_connection"`
ReferralFriends string `json:"referral_friends"`
ReferralApply string `json:"referral_apply"`
ReferralOutlet string `json:"referral_outlet"`
InterestDate string `json:"interest_date"`
MPI bool `json:"mpi"`
Notes string `json:"notes"`
VisionWall string `json:"vision_wall"`
MPPRequirements string `json:"mpp_requirements"`
VotingAgreement bool `json:"voting_agreement"`
StreetAddress string `json:"street_address"`
City string `json:"city"`
State string `json:"state"`
GeoCircles string `json:"geo_circles"`
Lat float64 `json:"lat"`
Lng float64 `json:"lng"`
AssignedTo int `json:"assigned_to"`
AssignedToName string `json:"assigned_to_name"`
FollowupDate string `json:"followup_date"`
TotalInteractions int `json:"total_interactions"`
LastInteractionDate string `json:"last_interaction_date"`
Email string `json:"email,omitempty"`
Facebook string `json:"facebook,omitempty"`
ID int `json:"id,omitempty"`
Location string `json:"location,omitempty"`
Name string `json:"name,omitempty"`
PreferredName string `json:"preferred_name,omitempty"`
Phone string `json:"phone,omitempty"`
Pronouns string `json:"pronouns,omitempty"`
Language string `json:"language,omitempty"`
Accessibility string `json:"accessibility,omitempty"`
Birthday string `json:"dob,omitempty"`
ChapterID int `json:"chapter_id,omitempty"`

FirstEvent string `json:"first_event,omitempty"`
LastEvent string `json:"last_event,omitempty"`
FirstEventName string `json:"first_event_name,omitempty"`
LastEventName string `json:"last_event_name,omitempty"`
LastAction string `json:"last_action,omitempty"`
MonthsSinceLastAction int `json:"months_since_last_action,omitempty"`
TotalEvents int `json:"total_events,omitempty"`
TotalPoints int `json:"total_points,omitempty"`
Active bool `json:"active,omitempty"`
Status string `json:"status,omitempty"`

ActivistLevel string `json:"activist_level,omitempty"`
Source string `json:"source,omitempty"`
Hiatus bool `json:"hiatus,omitempty"`

Connector string `json:"connector,omitempty"`
Training0 string `json:"training0,omitempty"`
Training1 string `json:"training1,omitempty"`
Training4 string `json:"training4,omitempty"`
Training5 string `json:"training5,omitempty"`
Training6 string `json:"training6,omitempty"`
ConsentQuiz string `json:"consent_quiz,omitempty"`
TrainingProtest string `json:"training_protest,omitempty"`
ApplicationDate string `json:"dev_application_date,omitempty"`
ApplicationType string `json:"dev_application_type,omitempty"`
Quiz string `json:"dev_quiz,omitempty"`
DevInterest string `json:"dev_interest,omitempty"`

CMFirstEmail string `json:"cm_first_email,omitempty"`
CMApprovalEmail string `json:"cm_approval_email,omitempty"`
ProspectOrganizer bool `json:"prospect_organizer,omitempty"`
ProspectChapterMember bool `json:"prospect_chapter_member,omitempty"`
LastConnection string `json:"last_connection,omitempty"`
ReferralFriends string `json:"referral_friends,omitempty"`
ReferralApply string `json:"referral_apply,omitempty"`
ReferralOutlet string `json:"referral_outlet,omitempty"`
InterestDate string `json:"interest_date,omitempty"`
MPI bool `json:"mpi,omitempty"`
Notes string `json:"notes,omitempty"`
VisionWall string `json:"vision_wall,omitempty"`
MPPRequirements string `json:"mpp_requirements,omitempty"`
VotingAgreement bool `json:"voting_agreement,omitempty"`
StreetAddress string `json:"street_address,omitempty"`
City string `json:"city,omitempty"`
State string `json:"state,omitempty"`
GeoCircles string `json:"geo_circles,omitempty"`
Lat float64 `json:"lat,omitempty"`
Lng float64 `json:"lng,omitempty"`
AssignedTo int `json:"assigned_to,omitempty"`
AssignedToName string `json:"assigned_to_name,omitempty"`
FollowupDate string `json:"followup_date,omitempty"`
TotalInteractions int `json:"total_interactions,omitempty"`
LastInteractionDate string `json:"last_interaction_date,omitempty"`
}

type GetActivistOptions struct {
Expand Down Expand Up @@ -575,18 +577,19 @@ func getActivistsJSON(db *sqlx.DB, options GetActivistOptions) ([]ActivistJSON,
if err != nil {
return nil, err
}
return buildActivistJSONArray(activists), nil
return BuildActivistJSONArray(activists), nil
}

func GetActivistRangeJSON(db *sqlx.DB, options ActivistRangeOptionsJSON) ([]ActivistJSON, error) {
activists, err := getActivistRange(db, options)
if err != nil {
return nil, err
}
return buildActivistJSONArray(activists), nil
return BuildActivistJSONArray(activists), nil
}

func buildActivistJSONArray(activists []ActivistExtra) []ActivistJSON {
// TODO: move to transport layer and make private once obsolete activist query options are removed.
func BuildActivistJSONArray(activists []ActivistExtra) []ActivistJSON {
var activistsJSON []ActivistJSON

for _, a := range activists {
Expand Down Expand Up @@ -2226,3 +2229,89 @@ func assignActivistToUser(db *sqlx.DB, activistID, userID int) error {
}
return nil
}

func QueryActivists(authedUser ADBUser, options QueryActivistOptions, repo ActivistRepository) (QueryActivistResult, error) {
if !UserHasRole("admin", authedUser) {
if authedUser.ChapterID != options.Filters.ChapterId || authedUser.ChapterID == 0 {
return QueryActivistResult{}, fmt.Errorf("Cannot query activists in other chapters without admin access")
}
}

if !UserHasAnyRole([]string{"admin", "organizer", "non-sfbay"}, authedUser) {
return QueryActivistResult{}, fmt.Errorf("Lacking permission to query activists")
}

options.normalizeAndValidate()

return repo.QueryActivists(options)
}

// Interface for querying and updating activists. This avoids a dependency on the persistence package which could create
// a cyclical package reference.
type ActivistRepository interface {
QueryActivists(options QueryActivistOptions) (QueryActivistResult, error)
}

type ActivistColumnName string

type QueryActivistOptions struct {
// This model is currently shared with the transport layer and treated as part of the frontend API.
// Introduce transport DTOs when the wire format needs to differ from internal semantics.

Columns []ActivistColumnName `json:"columns"`
Filters QueryActivistFilters `json:"filters"`
Sort ActivistSortOptions `json:"sort"`

// Cursor pointing to last item in previous page (base 64 encoding of values of sort columns and ID).
// Must be a value returned by QueryActivistResultPagination.NextCursor.
// If empty, the first page of results will be returned.
// If invalid, an error is returned.
After string `json:"after"`
}

type QueryActivistFilters struct {
// 0 means search all chapters. Requires that the "chapter" column be requested.
// Must be set to ID of current chapter if user only has permission for current chapter.
ChapterId int `json:"chapter_id"`
Name ActivistNameFilter `json:"name"`
LastEvent LastEventFilter `json:"last_event"`
IncludeHidden bool `json:"include_hidden"`
}

type ActivistNameFilter struct {
Name string `json:"name"`
}

type LastEventFilter struct {
LastEventLt *time.Time `json:"last_event_lt"`
LastEventGt *time.Time `json:"last_event_gt"`
}

type ActivistSortOptions struct {
SortColumns []ActivistSortColumn `json:"sort_columns"`
}

type ActivistSortColumn struct {
ColumnName ActivistColumnName `json:"column_name"`
Desc bool `json:"desc"`
}

type QueryActivistResult struct {
Activists []ActivistExtra `json:"activists"`
Pagination QueryActivistResultPagination `json:"pagination"`
}

type QueryActivistResultPagination struct {
// An opaque string if more results are available; otherwise, the empty string.
NextCursor string `json:"next_cursor"`
}

func (o *QueryActivistOptions) normalizeAndValidate() error {
// TODO: remove invalid characters from o.nameFilter.name

if o.Filters.ChapterId == 0 && !slices.Contains(o.Columns, "chapter") {
return fmt.Errorf("Must choose 'chapter' column when not filtering by chapter ID.")
}

return nil
}
20 changes: 20 additions & 0 deletions server/src/model/adb_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,26 @@ func ValidateADBUser(user ADBUser) error {
return nil
}

func UserHasAnyRole(roles []string, user ADBUser) bool {
for i := 0; i < len(roles); i++ {
if UserHasRole(roles[i], user) {
return true
}
}

return false
}

func UserHasRole(role string, user ADBUser) bool {
for _, r := range user.Roles {
if r == role {
return true
}
}

return false
}

// Interface for querying and updating users. This avoids a dependency on the persistence package which could create a
// cyclical package reference.
type UserRepository interface {
Expand Down
Loading