reprogl

Форк
0
/
profile.go 
140 строк · 3.4 Кб
1
package handlers
2

3
import (
4
	"errors"
5
	"net/http"
6

7
	"xelbot.com/reprogl/api/backend"
8
	"xelbot.com/reprogl/container"
9
	"xelbot.com/reprogl/models"
10
	"xelbot.com/reprogl/models/repositories"
11
	"xelbot.com/reprogl/session"
12
	"xelbot.com/reprogl/views"
13
)
14

15
type updateProfileResponse struct {
16
	Valid  bool                `json:"valid"`
17
	Errors []backend.FormError `json:"errors,omitempty"`
18
}
19

20
func ProfileAction(app *container.Application) http.HandlerFunc {
21
	return func(w http.ResponseWriter, r *http.Request) {
22
		// TODO move to middleware
23
		if !session.HasIdentity(r.Context()) {
24
			http.Redirect(w, r, container.GenerateURL("login"), http.StatusFound)
25
			return
26
		}
27

28
		var user *models.User
29
		if identity, ok := session.GetIdentity(r.Context()); ok {
30
			repo := repositories.UserRepository{DB: app.DB}
31
			user, _ = repo.Find(identity.ID)
32
		}
33

34
		if user == nil {
35
			app.ServerError(w, errors.New("profile logic error: user is null"))
36
			return
37
		}
38

39
		subscriptionSettingsRepo := repositories.EmailSubscriptionRepository{DB: app.DB}
40
		subscrSettings, err := subscriptionSettingsRepo.FindOrCreate(user.Email, models.SubscriptionReplyComment)
41
		if err != nil {
42
			app.ServerError(w, err)
43
			return
44
		}
45

46
		templateData := views.NewProfilePageData(user, subscrSettings)
47
		err = views.WriteTemplate(w, "profile.gohtml", templateData)
48
		if err != nil {
49
			app.ServerError(w, err)
50

51
			return
52
		}
53
	}
54
}
55

56
func UpdateProfile(app *container.Application) http.HandlerFunc {
57
	return func(w http.ResponseWriter, r *http.Request) {
58
		// TODO move to middleware
59
		if !session.HasIdentity(r.Context()) {
60
			http.Redirect(w, r, container.GenerateURL("login"), http.StatusFound)
61
			return
62
		}
63

64
		var user *models.User
65
		if identity, ok := session.GetIdentity(r.Context()); ok {
66
			repo := repositories.UserRepository{DB: app.DB}
67
			user, _ = repo.Find(identity.ID)
68
		}
69

70
		if user == nil {
71
			app.ServerError(w, errors.New("profile logic error: user is null"))
72
			return
73
		}
74

75
		profileData := backend.ProfileDTO{
76
			ID:          user.ID,
77
			Role:        user.Role,
78
			Username:    r.PostFormValue("username"),
79
			Email:       r.PostFormValue("email"),
80
			DisplayName: r.PostFormValue("displayName"),
81
		}
82

83
		if r.PostFormValue("gender") == "male" {
84
			profileData.IsMale = true
85
		} else {
86
			profileData.IsMale = false
87
		}
88

89
		var responseData any
90
		statusCode := http.StatusOK
91

92
		apiResponse, err := backend.SendProfileData(profileData)
93
		if err != nil {
94
			app.ServerError(w, err)
95

96
			return
97
		}
98

99
		if apiResponse != nil {
100
			result := updateProfileResponse{
101
				Valid:  true,
102
				Errors: apiResponse.Violations,
103
			}
104

105
			if apiResponse.Violations != nil && len(apiResponse.Violations) > 0 {
106
				result.Valid = false
107
			}
108

109
			responseData = result
110

111
			if apiResponse.User != nil {
112
				subscriptionSettingsRepo := repositories.EmailSubscriptionRepository{DB: app.DB}
113
				subscrSettings, err := subscriptionSettingsRepo.FindOrCreate(
114
					apiResponse.User.Email,
115
					models.SubscriptionReplyComment)
116
				if err != nil {
117
					app.ServerError(w, err)
118
					return
119
				}
120

121
				formValue := r.PostFormValue("reply_subscribe")
122
				if formValue != "" {
123
					if subscrSettings.BlockSending {
124
						err = subscriptionSettingsRepo.Subscribe(subscrSettings.ID)
125
					}
126
				} else {
127
					if !subscrSettings.BlockSending {
128
						err = subscriptionSettingsRepo.Unsubscribe(subscrSettings.ID)
129
					}
130
				}
131
				if err != nil {
132
					app.ServerError(w, err)
133
					return
134
				}
135
			}
136
		}
137

138
		jsonResponse(w, statusCode, responseData)
139
	}
140
}
141

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.