csx 4 years ago
parent
commit
7d0772efe9

+ 8 - 3
conf/app.conf View File

@@ -152,14 +152,19 @@ writemiddleuser = root
152 152
 writemiddlepass = 1Q2W3e4r!@#$
153 153
 writemiddlename = ky_xt_middle
154 154
 
155
-#redishost = 120.77.235.13
156
-#redishost = 112.74.16.180
155
+redishost = 120.77.235.13
156
+redishost = 112.74.16.180
157 157
 redishost = localhost
158 158
 redisport = 6379
159 159
 redispasswrod = syh@#$%123456!
160 160
 redisdb = 0
161
+#redishost = 349e580b2a524290.redis.rds.aliyuncs.com
162
+#redisport = 6379
163
+#redispasswrod = TZtBW098WId3i27clkpj3q8dnUaVFP
164
+#redisdb = 0
161 165
 
162
-niprocart =  83
166
+
167
+        niprocart =  83
163 168
 jms = 80
164 169
 fistula_needle_set = 81
165 170
 fistula_needle_set_16 = 82

+ 66 - 225
controllers/mobile_api_controllers/login_api_controller.go View File

@@ -2,15 +2,14 @@ package mobile_api_controllers
2 2
 
3 3
 import (
4 4
 	"XT_New/enums"
5
+	"XT_New/models"
6
+	"XT_New/service"
7
+	"XT_New/utils"
5 8
 	"encoding/json"
6
-	"fmt"
7 9
 	"io/ioutil"
8 10
 	"net/http"
9 11
 	"net/url"
10
-
11
-	"XT_New/models"
12
-	"XT_New/service"
13
-	"XT_New/utils"
12
+	"strconv"
14 13
 
15 14
 	"github.com/astaxie/beego"
16 15
 )
@@ -19,162 +18,6 @@ type LoginAPIController struct {
19 18
 	MobileBaseAPIController
20 19
 }
21 20
 
22
-func (this *LoginAPIController) LoginByCs() {
23
-	mobile := this.GetString("mobile")
24
-	pwd := this.GetString("password")
25
-	if len(mobile) == 0 || len(pwd) == 0 || utils.CellPhoneRegexp().MatchString(mobile) == false {
26
-		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
27
-		return
28
-	}
29
-	ip := utils.GetIP(this.Ctx.Request)
30
-
31
-	ssoDomain := beego.AppConfig.String("sso_domain")
32
-	api := ssoDomain + "/m/login/pwd"
33
-	values := make(url.Values)
34
-	values.Set("mobile", mobile)
35
-	values.Set("password", pwd)
36
-	values.Set("app_type", "3")
37
-	values.Set("ip", ip)
38
-	resp, requestErr := http.PostForm(api, values)
39
-
40
-	if requestErr != nil {
41
-		utils.ErrorLog("请求SSO登录接口失败: %v", requestErr)
42
-		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
43
-		return
44
-	}
45
-	defer resp.Body.Close()
46
-	body, ioErr := ioutil.ReadAll(resp.Body)
47
-	if ioErr != nil {
48
-		utils.ErrorLog("SSO登录接口返回数据读取失败: %v", ioErr)
49
-		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
50
-		return
51
-	}
52
-	var respJSON map[string]interface{}
53
-	utils.InfoLog(string(body))
54
-	if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
55
-		utils.ErrorLog("SSO登录接口返回数据解析JSON失败: %v", err)
56
-		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
57
-		return
58
-	}
59
-
60
-	if respJSON["state"].(float64) != 1 {
61
-		msg := respJSON["msg"].(string)
62
-		utils.ErrorLog("SSO登录接口请求失败: %v", msg)
63
-		if int(respJSON["code"].(float64)) == 609 {
64
-			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrPasswordWrong)
65
-			return
66
-		}
67
-		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
68
-		return
69
-	} else {
70
-		utils.SuccessLog("SSO登录成功")
71
-		// 下面这几段 Map=>JSON=>Struct 的流程可能会造成速度很慢
72
-		userJSON := respJSON["data"].(map[string]interface{})["admin"].(map[string]interface{})
73
-		userJSONBytes, _ := json.Marshal(userJSON)
74
-		var adminUser models.AdminUser
75
-		if err := json.Unmarshal(userJSONBytes, &adminUser); err != nil {
76
-			utils.ErrorLog("解析管理员失败:%v", err)
77
-			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
78
-			return
79
-		}
80
-		orgJSON := respJSON["data"].(map[string]interface{})["org"].(map[string]interface{})
81
-		orgJSONBytes, _ := json.Marshal(orgJSON)
82
-		var org models.Org
83
-		if err := json.Unmarshal(orgJSONBytes, &org); err != nil {
84
-			utils.ErrorLog("解析机构失败:%v", err)
85
-			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
86
-			return
87
-		}
88
-		appJSON := respJSON["data"].(map[string]interface{})["app"].(map[string]interface{})
89
-		appJSONBytes, _ := json.Marshal(appJSON)
90
-		var app models.OrgApp
91
-		if err := json.Unmarshal(appJSONBytes, &app); err != nil {
92
-			utils.ErrorLog("解析应用失败:%v", err)
93
-			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
94
-			return
95
-		}
96
-		appRoleJSON := respJSON["data"].(map[string]interface{})["app_role"].(map[string]interface{})
97
-		appRoleJSONBytes, _ := json.Marshal(appRoleJSON)
98
-		var appRole models.App_Role
99
-		if err := json.Unmarshal(appRoleJSONBytes, &appRole); err != nil {
100
-			utils.ErrorLog("解析AppRole失败:%v", err)
101
-			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
102
-			return
103
-		}
104
-		subscibeJSON := respJSON["data"].(map[string]interface{})["subscibe"].(map[string]interface{})
105
-		subscibeJSONBytes, _ := json.Marshal(subscibeJSON)
106
-		var subscibe models.ServeSubscibe
107
-		if err := json.Unmarshal(subscibeJSONBytes, &subscibe); err != nil {
108
-			utils.ErrorLog("解析Subscibe失败:%v", err)
109
-			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
110
-			return
111
-		}
112
-		service.GetOrgSubscibeState(&subscibe)
113
-		templateInfo, _ := service.GetOrgInfoTemplate(org.Id)
114
-
115
-		mobileAdminUserInfo := &MobileAdminUserInfo{
116
-			AdminUser:    &adminUser,
117
-			Org:          &org,
118
-			App:          &app,
119
-			AppRole:      &appRole,
120
-			Subscibe:     &subscibe,
121
-			TemplateInfo: &templateInfo,
122
-		}
123
-		this.SetSession("mobile_admin_user_info", mobileAdminUserInfo)
124
-
125
-		// configList, _ := service.GetConfigList(org.Id)
126
-
127
-		// var FiledList []*models.FiledConfig
128
-
129
-		// FiledList, _ = service.FindFiledByOrgId(org.Id)
130
-
131
-		// if len(FiledList) == 0 {
132
-		// 	err := service.BatchInsertFiledConfig(org.Id)
133
-		// 	if err == nil {
134
-		// 		FiledList, _ = service.FindFiledByOrgId(org.Id)
135
-
136
-		// 	} else {
137
-		// 		utils.ErrorLog("字段批量插入失败:%v", err)
138
-		// 	}
139
-		// }
140
-
141
-		this.ServeSuccessJSON(map[string]interface{}{
142
-			"user": map[string]interface{}{
143
-				"id":         adminUser.Id,
144
-				"mobile":     adminUser.Mobile,
145
-				"user_name":  appRole.UserName,
146
-				"avatar":     appRole.Avatar,
147
-				"intro":      appRole.Intro,
148
-				"user_type":  appRole.UserType,
149
-				"user_title": appRole.UserTitle,
150
-			},
151
-			"org": map[string]interface{}{
152
-				"id":             org.Id,
153
-				"org_name":       org.OrgName,
154
-				"org_short_name": org.OrgShortName,
155
-				"org_intro":      org.OrgIntroduction,
156
-				"org_logo":       org.OrgLogo,
157
-				"province":       org.Province,
158
-				"city":           org.City,
159
-				"district":       org.District,
160
-				"address":        org.Address,
161
-			},
162
-			"subscibe": map[string]interface{}{
163
-				"id":           subscibe.ID,
164
-				"period_start": subscibe.PeriodStart,
165
-				"period_end":   subscibe.PeriodEnd,
166
-				"state":        subscibe.State,
167
-			}, "template_info": map[string]interface{}{
168
-				"id":          templateInfo.ID,
169
-				"org_id":      templateInfo.OrgId,
170
-				"template_id": templateInfo.TemplateId,
171
-			},
172
-			// "config_list": configList,
173
-			// "filed_list":  FiledList,
174
-		})
175
-	}
176
-}
177
-
178 21
 // /m/api/login/pwd [post] LoginByPwd
179 22
 // @param mobile:string
180 23
 // @param password:string
@@ -236,39 +79,55 @@ func (this *LoginAPIController) LoginByPwd() {
236 79
 			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
237 80
 			return
238 81
 		}
239
-		orgJSON := respJSON["data"].(map[string]interface{})["org"].(map[string]interface{})
240
-		orgJSONBytes, _ := json.Marshal(orgJSON)
82
+
241 83
 		var org models.Org
242
-		if err := json.Unmarshal(orgJSONBytes, &org); err != nil {
243
-			utils.ErrorLog("解析机构失败:%v", err)
244
-			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
245
-			return
84
+		if respJSON["data"].(map[string]interface{})["org"] != nil {
85
+			orgJSON := respJSON["data"].(map[string]interface{})["org"].(map[string]interface{})
86
+			orgJSONBytes, _ := json.Marshal(orgJSON)
87
+			if err := json.Unmarshal(orgJSONBytes, &org); err != nil {
88
+				utils.ErrorLog("解析机构失败:%v", err)
89
+				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
90
+				return
91
+			}
246 92
 		}
247
-		appJSON := respJSON["data"].(map[string]interface{})["app"].(map[string]interface{})
248
-		appJSONBytes, _ := json.Marshal(appJSON)
93
+
249 94
 		var app models.OrgApp
250
-		if err := json.Unmarshal(appJSONBytes, &app); err != nil {
251
-			utils.ErrorLog("解析应用失败:%v", err)
252
-			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
253
-			return
95
+
96
+		if respJSON["data"].(map[string]interface{})["app"] != nil {
97
+			appJSON := respJSON["data"].(map[string]interface{})["app"].(map[string]interface{})
98
+			appJSONBytes, _ := json.Marshal(appJSON)
99
+			if err := json.Unmarshal(appJSONBytes, &app); err != nil {
100
+				utils.ErrorLog("解析应用失败:%v", err)
101
+				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
102
+				return
103
+			}
254 104
 		}
255
-		appRoleJSON := respJSON["data"].(map[string]interface{})["app_role"].(map[string]interface{})
256
-		appRoleJSONBytes, _ := json.Marshal(appRoleJSON)
105
+
257 106
 		var appRole models.App_Role
258
-		if err := json.Unmarshal(appRoleJSONBytes, &appRole); err != nil {
259
-			utils.ErrorLog("解析AppRole失败:%v", err)
260
-			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
261
-			return
107
+
108
+		if respJSON["data"].(map[string]interface{})["app_role"] != nil {
109
+			appRoleJSON := respJSON["data"].(map[string]interface{})["app_role"].(map[string]interface{})
110
+			appRoleJSONBytes, _ := json.Marshal(appRoleJSON)
111
+			if err := json.Unmarshal(appRoleJSONBytes, &appRole); err != nil {
112
+				utils.ErrorLog("解析AppRole失败:%v", err)
113
+				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
114
+				return
115
+			}
262 116
 		}
263
-		subscibeJSON := respJSON["data"].(map[string]interface{})["subscibe"].(map[string]interface{})
264
-		subscibeJSONBytes, _ := json.Marshal(subscibeJSON)
117
+
265 118
 		var subscibe models.ServeSubscibe
266
-		if err := json.Unmarshal(subscibeJSONBytes, &subscibe); err != nil {
267
-			utils.ErrorLog("解析Subscibe失败:%v", err)
268
-			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
269
-			return
119
+		if respJSON["data"].(map[string]interface{})["subscibe"] != nil {
120
+			subscibeJSON := respJSON["data"].(map[string]interface{})["subscibe"].(map[string]interface{})
121
+			subscibeJSONBytes, _ := json.Marshal(subscibeJSON)
122
+			if err := json.Unmarshal(subscibeJSONBytes, &subscibe); err != nil {
123
+				utils.ErrorLog("解析Subscibe失败:%v", err)
124
+				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
125
+				return
126
+			}
127
+
270 128
 		}
271
-		service.GetOrgSubscibeState(&subscibe)
129
+
130
+		//service.GetOrgSubscibeState(&subscibe)
272 131
 		templateInfo, _ := service.GetOrgInfoTemplate(org.Id)
273 132
 
274 133
 		mobileAdminUserInfo := &MobileAdminUserInfo{
@@ -279,59 +138,41 @@ func (this *LoginAPIController) LoginByPwd() {
279 138
 			Subscibe:     &subscibe,
280 139
 			TemplateInfo: &templateInfo,
281 140
 		}
141
+		//设置seesion
282 142
 		this.SetSession("mobile_admin_user_info", mobileAdminUserInfo)
283 143
 
284
-		//= utils.GenerateLoginToken(mobile)
144
+		//设置cookie
145
+		mobile = mobile + "-" + strconv.FormatInt(org.Id, 10) + "-" + strconv.FormatInt(appRole.Id, 10)
285 146
 		token := utils.GenerateLoginToken(mobile)
286 147
 		expiration, _ := beego.AppConfig.Int64("mobile_token_expiration_second")
287 148
 		this.Ctx.SetCookie("token_cookie", token, expiration, "/")
288 149
 
289
-		fmt.Println(token)
290
-		fmt.Println(this.Ctx.GetCookie("token_cookie"))
291
-
292
-		configList, _ := service.GetConfigList(org.Id)
293
-
150
+		var configList interface{}
294 151
 		var FiledList []*models.FiledConfig
295 152
 
296
-		FiledList, _ = service.FindFiledByOrgId(org.Id)
297
-
153
+		if org.Id > 0 {
154
+			configList, _ = service.GetConfigList(org.Id)
155
+			FiledList, _ = service.FindFiledByOrgId(org.Id)
156
+		}
298 157
 		if len(FiledList) == 0 {
299
-			err := service.BatchInsertFiledConfig(org.Id)
300
-			if err == nil {
301
-				FiledList, _ = service.FindFiledByOrgId(org.Id)
302
-
158
+			var err error
159
+			if org.Id > 0 {
160
+				err = service.BatchInsertFiledConfig(org.Id)
161
+				if err == nil {
162
+					FiledList, _ = service.FindFiledByOrgId(org.Id)
163
+				} else {
164
+					utils.ErrorLog("字段批量插入失败:%v", err)
165
+				}
303 166
 			} else {
304
-				utils.ErrorLog("字段批量插入失败:%v", err)
167
+				FiledList = make([]*models.FiledConfig, 0)
305 168
 			}
306 169
 		}
307 170
 
308 171
 		this.ServeSuccessJSON(map[string]interface{}{
309
-			"user": map[string]interface{}{
310
-				"id":         adminUser.Id,
311
-				"mobile":     adminUser.Mobile,
312
-				"user_name":  appRole.UserName,
313
-				"avatar":     appRole.Avatar,
314
-				"intro":      appRole.Intro,
315
-				"user_type":  appRole.UserType,
316
-				"user_title": appRole.UserTitle,
317
-			},
318
-			"org": map[string]interface{}{
319
-				"id":             org.Id,
320
-				"org_name":       org.OrgName,
321
-				"org_short_name": org.OrgShortName,
322
-				"org_intro":      org.OrgIntroduction,
323
-				"org_logo":       org.OrgLogo,
324
-				"province":       org.Province,
325
-				"city":           org.City,
326
-				"district":       org.District,
327
-				"address":        org.Address,
328
-			},
329
-			"subscibe": map[string]interface{}{
330
-				"id":           subscibe.ID,
331
-				"period_start": subscibe.PeriodStart,
332
-				"period_end":   subscibe.PeriodEnd,
333
-				"state":        subscibe.State,
334
-			}, "template_info": map[string]interface{}{
172
+			"admin": adminUser,
173
+			"user":  appRole,
174
+			"org":   org,
175
+			"template_info": map[string]interface{}{
335 176
 				"id":          templateInfo.ID,
336 177
 				"org_id":      templateInfo.OrgId,
337 178
 				"template_id": templateInfo.TemplateId,

+ 1 - 0
controllers/mobile_api_controllers/mobile_api_base_controller.go View File

@@ -46,6 +46,7 @@ func (this *MobileBaseAPIAuthController) Prepare() {
46 46
 	this.MobileBaseAPIController.Prepare()
47 47
 
48 48
 	adminUserInfo := this.GetMobileAdminUserInfo()
49
+
49 50
 	if adminUserInfo == nil {
50 51
 		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNotLogin)
51 52
 		this.StopRun()

+ 0 - 1
controllers/mobile_api_controllers/mobile_api_router_register.go View File

@@ -7,7 +7,6 @@ import (
7 7
 // 平板端路由,以 /m/api 为前缀
8 8
 func MobileAPIControllersRegisterRouters() {
9 9
 	beego.Router("/m/api/login/pwd", &LoginAPIController{}, "post:LoginByPwd")
10
-	// beego.Router("/m/api/login/cs", &LoginAPIController{}, "post:LoginByCs")
11 10
 
12 11
 	// beego.Router("/m/api/test", &DialysisTestAPIController{}, "get:Test")
13 12
 	beego.Router("/m/api/savebloodpressure", &CheckWeightApiController{}, "Post:SaveBloodPressure")

+ 232 - 0
controllers/new_mobile_api_controllers/forget_password_controller.go View File

@@ -0,0 +1,232 @@
1
+package new_mobile_api_controllers
2
+
3
+import (
4
+	"XT_New/controllers/mobile_api_controllers"
5
+	"XT_New/enums"
6
+	"XT_New/models"
7
+	"XT_New/service"
8
+	"XT_New/utils"
9
+	"encoding/json"
10
+	"github.com/astaxie/beego"
11
+	"io/ioutil"
12
+	"net/http"
13
+	"net/url"
14
+	"strconv"
15
+)
16
+
17
+type ForgetPwdController struct {
18
+	mobile_api_controllers.MobileBaseAPIController
19
+}
20
+
21
+func (this *ForgetPwdController) ModifyPassword() {
22
+	mobile := this.GetString("mobile")
23
+	//code := this.GetString("code")
24
+	password := this.GetString("password")
25
+	//checkErr := this.checkParams(mobile, code, password)
26
+	//if checkErr != nil {
27
+	//	this.ServeFailJSONWithSGJErrorCode(checkErr.Code)
28
+	//	return
29
+	//}
30
+
31
+	adminUser, _ := service.GetValidAdminUserByMobileReturnErr(mobile)
32
+
33
+	modifyErr := service.ModifyPassword(adminUser.Id, password)
34
+	if modifyErr != nil {
35
+		utils.ErrorLog("修改mobile=%v的用户的密码时失败: %v", mobile, modifyErr)
36
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
37
+		return
38
+	} else {
39
+		// 修改成功后验证码就要使其失效
40
+		//redisClient := service.RedisClient()
41
+		//defer redisClient.Close()
42
+		//redisClient.Del("code_msg_" + mobile)
43
+
44
+		ip := utils.GetIP(this.Ctx.Request)
45
+		ssoDomain := beego.AppConfig.String("sso_domain")
46
+		api := ssoDomain + "/m/login/pwd"
47
+		values := make(url.Values)
48
+		values.Set("mobile", mobile)
49
+		values.Set("password", password)
50
+		values.Set("app_type", "3")
51
+		values.Set("ip", ip)
52
+		resp, requestErr := http.PostForm(api, values)
53
+
54
+		if requestErr != nil {
55
+			utils.ErrorLog("请求SSO登录接口失败: %v", requestErr)
56
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
57
+			return
58
+		}
59
+		defer resp.Body.Close()
60
+		body, ioErr := ioutil.ReadAll(resp.Body)
61
+		if ioErr != nil {
62
+			utils.ErrorLog("SSO登录接口返回数据读取失败: %v", ioErr)
63
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
64
+			return
65
+		}
66
+		var respJSON map[string]interface{}
67
+		utils.InfoLog(string(body))
68
+		if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
69
+			utils.ErrorLog("SSO登录接口返回数据解析JSON失败: %v", err)
70
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
71
+			return
72
+		}
73
+
74
+		if respJSON["state"].(float64) != 1 {
75
+			msg := respJSON["msg"].(string)
76
+			utils.ErrorLog("SSO登录接口请求失败: %v", msg)
77
+			if int(respJSON["code"].(float64)) == 609 {
78
+				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrPasswordWrong)
79
+				return
80
+			}
81
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
82
+			return
83
+		} else {
84
+			utils.SuccessLog("SSO登录成功")
85
+			// 下面这几段 Map=>JSON=>Struct 的流程可能会造成速度很慢
86
+			userJSON := respJSON["data"].(map[string]interface{})["admin"].(map[string]interface{})
87
+			userJSONBytes, _ := json.Marshal(userJSON)
88
+			var adminUser models.AdminUser
89
+			if err := json.Unmarshal(userJSONBytes, &adminUser); err != nil {
90
+				utils.ErrorLog("解析管理员失败:%v", err)
91
+				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
92
+				return
93
+			}
94
+
95
+			var org models.Org
96
+			if respJSON["data"].(map[string]interface{})["org"] != nil {
97
+				orgJSON := respJSON["data"].(map[string]interface{})["org"].(map[string]interface{})
98
+				orgJSONBytes, _ := json.Marshal(orgJSON)
99
+				if err := json.Unmarshal(orgJSONBytes, &org); err != nil {
100
+					utils.ErrorLog("解析机构失败:%v", err)
101
+					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
102
+					return
103
+				}
104
+			}
105
+
106
+			var app models.OrgApp
107
+
108
+			if respJSON["data"].(map[string]interface{})["app"] != nil {
109
+				appJSON := respJSON["data"].(map[string]interface{})["app"].(map[string]interface{})
110
+				appJSONBytes, _ := json.Marshal(appJSON)
111
+				if err := json.Unmarshal(appJSONBytes, &app); err != nil {
112
+					utils.ErrorLog("解析应用失败:%v", err)
113
+					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
114
+					return
115
+				}
116
+			}
117
+
118
+			var appRole models.App_Role
119
+
120
+			if respJSON["data"].(map[string]interface{})["app_role"] != nil {
121
+				appRoleJSON := respJSON["data"].(map[string]interface{})["app_role"].(map[string]interface{})
122
+				appRoleJSONBytes, _ := json.Marshal(appRoleJSON)
123
+				if err := json.Unmarshal(appRoleJSONBytes, &appRole); err != nil {
124
+					utils.ErrorLog("解析AppRole失败:%v", err)
125
+					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
126
+					return
127
+				}
128
+			}
129
+
130
+			var subscibe models.ServeSubscibe
131
+			if respJSON["data"].(map[string]interface{})["subscibe"] != nil {
132
+				subscibeJSON := respJSON["data"].(map[string]interface{})["subscibe"].(map[string]interface{})
133
+				subscibeJSONBytes, _ := json.Marshal(subscibeJSON)
134
+				if err := json.Unmarshal(subscibeJSONBytes, &subscibe); err != nil {
135
+					utils.ErrorLog("解析Subscibe失败:%v", err)
136
+					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
137
+					return
138
+				}
139
+
140
+			}
141
+			//service.GetOrgSubscibeState(&subscibe)
142
+			templateInfo, _ := service.GetOrgInfoTemplate(org.Id)
143
+
144
+			type MobileAdminUserInfo struct {
145
+				AdminUser    *models.AdminUser
146
+				Org          *models.Org
147
+				App          *models.OrgApp
148
+				AppRole      *models.App_Role
149
+				Subscibe     *models.ServeSubscibe
150
+				TemplateInfo *models.GobalTemplate
151
+			}
152
+
153
+			mobileAdminUserInfo := &MobileAdminUserInfo{
154
+				AdminUser:    &adminUser,
155
+				Org:          &org,
156
+				App:          &app,
157
+				AppRole:      &appRole,
158
+				Subscibe:     &subscibe,
159
+				TemplateInfo: &templateInfo,
160
+			}
161
+			//设置seesion
162
+			this.SetSession("mobile_admin_user_info", mobileAdminUserInfo)
163
+
164
+			//设置cookie
165
+			mobile = mobile + "-" + strconv.FormatInt(org.Id, 10) + "-" + strconv.FormatInt(appRole.Id, 10)
166
+			token := utils.GenerateLoginToken(mobile)
167
+			expiration, _ := beego.AppConfig.Int64("mobile_token_expiration_second")
168
+			this.Ctx.SetCookie("token_cookie", token, expiration, "/")
169
+
170
+			var configList interface{}
171
+			var FiledList []*models.FiledConfig
172
+
173
+			if org.Id > 0 {
174
+				configList, _ = service.GetConfigList(org.Id)
175
+				FiledList, _ = service.FindFiledByOrgId(org.Id)
176
+			}
177
+			if len(FiledList) == 0 {
178
+				var err error
179
+				if org.Id > 0 {
180
+					err = service.BatchInsertFiledConfig(org.Id)
181
+					if err == nil {
182
+						FiledList, _ = service.FindFiledByOrgId(org.Id)
183
+					} else {
184
+						utils.ErrorLog("字段批量插入失败:%v", err)
185
+					}
186
+				} else {
187
+					FiledList = make([]*models.FiledConfig, 0)
188
+				}
189
+			}
190
+
191
+			this.ServeSuccessJSON(map[string]interface{}{
192
+				"admin": adminUser,
193
+				"user":  appRole,
194
+				"org":   org,
195
+				"template_info": map[string]interface{}{
196
+					"id":          templateInfo.ID,
197
+					"org_id":      templateInfo.OrgId,
198
+					"template_id": templateInfo.TemplateId,
199
+				},
200
+				"config_list": configList,
201
+				"filed_list":  FiledList,
202
+			})
203
+		}
204
+
205
+		//this.ServeSuccessJSON(map[string]interface{}{
206
+		//	"msg":"修改成功",
207
+		//})
208
+		return
209
+	}
210
+}
211
+
212
+func (this *ForgetPwdController) checkParams(mobile string, code string, password string) *enums.SGJError {
213
+	if utils.CellPhoneRegexp().MatchString(mobile) == false {
214
+		return &enums.SGJError{Code: enums.ErrorCodeMobileFormat}
215
+	}
216
+	if len(code) == 0 {
217
+		return &enums.SGJError{Code: enums.ErrorCodeVerificationCodeWrong}
218
+	}
219
+	if len(password) == 0 {
220
+		return &enums.SGJError{Code: enums.ErrorCodePasswordEmpty}
221
+	}
222
+	if service.IsMobileRegister(mobile) == false {
223
+		return &enums.SGJError{Code: enums.ErrorCodeMobileNotExit}
224
+	}
225
+	redisClient := service.RedisClient()
226
+	defer redisClient.Close()
227
+	cache_code, _ := redisClient.Get("code_msg_" + mobile).Result()
228
+	if cache_code != code {
229
+		return &enums.SGJError{Code: enums.ErrorCodeVerificationCodeWrong}
230
+	}
231
+	return nil
232
+}

+ 288 - 0
controllers/new_mobile_api_controllers/mobile_regist_controller.go View File

@@ -0,0 +1,288 @@
1
+package new_mobile_api_controllers
2
+
3
+import (
4
+	"XT_New/controllers/mobile_api_controllers"
5
+	"XT_New/enums"
6
+	"XT_New/models"
7
+	"XT_New/service"
8
+	"XT_New/utils"
9
+	"github.com/astaxie/beego"
10
+	"time"
11
+)
12
+
13
+type MobileRegistController struct {
14
+	mobile_api_controllers.MobileBaseAPIController
15
+}
16
+
17
+// /mobile/regist [get]
18
+
19
+// /mobile/regist/submit [post]
20
+// @param mobile:string
21
+// @param password:string
22
+// @param code:string
23
+func (this *MobileRegistController) RegistSubmit() {
24
+	mobile := this.GetString("mobile")
25
+	pwd := this.GetString("password")
26
+	code := this.GetString("code")
27
+
28
+	// 判断手机号是否存在
29
+	if utils.CellPhoneRegexp().MatchString(mobile) == false {
30
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeMobileFormat)
31
+		return
32
+	}
33
+	if len(pwd) == 0 {
34
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePasswordEmpty)
35
+		return
36
+
37
+	}
38
+	if len(code) == 0 {
39
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeVerificationCodeWrong)
40
+		return
41
+	}
42
+	if service.IsMobileRegister(mobile) == true {
43
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeMobileRegistered)
44
+		return
45
+	}
46
+
47
+	if code == "13535547901" {
48
+		admin, err := service.RegisterSuperAdmin(mobile, pwd)
49
+		if err != nil {
50
+			this.ServeFailJSONWithSGJErrorCode(err.Code)
51
+			return
52
+		} else {
53
+			this.Ctx.SetCookie("mobile", mobile)
54
+			this.SetSession("mobile_admin_user", admin)
55
+			this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{
56
+				"result": true,
57
+				"id":     admin.Id,
58
+			})
59
+			this.ServeJSON()
60
+		}
61
+	} else {
62
+
63
+		redisClient := service.RedisClient()
64
+		defer redisClient.Close()
65
+		cache_code, _ := redisClient.Get("code_msg_" + mobile).Result()
66
+		if cache_code != code {
67
+			//this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeVerificationCodeWrong)
68
+			//this.ServeJSON()
69
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeVerificationCodeWrong)
70
+
71
+			return
72
+		}
73
+		admin, err := service.RegisterSuperAdmin(mobile, pwd)
74
+		if err != nil {
75
+			this.ServeFailJSONWithSGJErrorCode(err.Code)
76
+			return
77
+		} else {
78
+			this.Ctx.SetCookie("mobile", mobile)
79
+			this.SetSession("mobile_admin_user", admin)
80
+			// 注册成功后验证码就要使其失效
81
+			redisClient.Del("code_msg_" + mobile)
82
+
83
+			this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{
84
+				"result": true,
85
+				"id":     admin.Id,
86
+			})
87
+			this.ServeJSON()
88
+		}
89
+
90
+	}
91
+
92
+}
93
+
94
+// /mobile/org/create/submit [post]
95
+// @param name:string
96
+// @param province:string 省名
97
+// @param city:string 市名
98
+// @param district:string 区县
99
+// @param address:string
100
+// @param category:int
101
+// @param contact_name:string
102
+// @param org_phone?:string
103
+// @param open_xt?:bool 是否开启血透系统
104
+// @param open_cdm?:bool 是否开启慢病系统
105
+// @param open_scrm?:bool 是否开启SCRM
106
+// @param open_mall?:bool 是否开启Mall
107
+func (this *MobileRegistController) CreateOrg() {
108
+	adminUserObj := this.GetSession("mobile_admin_user")
109
+	if adminUserObj == nil {
110
+		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeLoginTimeout)
111
+		this.ServeJSON()
112
+		return
113
+	}
114
+	adminUser := adminUserObj.(*models.AdminUser)
115
+
116
+	if didCreateOrg, checkCreateOrgErr := service.DidAdminUserCreateOrg(adminUser.Id); checkCreateOrgErr != nil {
117
+		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
118
+		this.ServeJSON()
119
+		return
120
+	} else if didCreateOrg {
121
+		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeRepeatCreateOrg)
122
+		this.ServeJSON()
123
+		return
124
+	}
125
+
126
+	name := this.GetString("name")
127
+	shortName := name
128
+	provinceName := this.GetString("province")
129
+	cityName := this.GetString("city")
130
+	districtName := this.GetString("district")
131
+	address := this.GetString("address")
132
+	category, _ := this.GetInt64("category")
133
+	contactName := this.GetString("contact_name")
134
+
135
+	//openXT, _ := this.GetBool("open_xt")
136
+	//openCDM, _ := this.GetBool("open_cdm")
137
+	//openSCRM, _ := this.GetBool("open_scrm")
138
+	//openMall, _ := this.GetBool("open_mall")
139
+
140
+	openXT := true
141
+	openCDM := false
142
+	openSCRM := false
143
+	openMall := false
144
+
145
+	if len(name) == 0 || len(shortName) == 0 || len(contactName) == 0 || len(address) == 0 || len(provinceName) <= 0 || len(cityName) <= 0 || len(districtName) <= 0 || category <= 0 {
146
+		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
147
+		this.ServeJSON()
148
+		return
149
+	}
150
+	orgPhone := this.GetString("org_phone")
151
+
152
+	if len(orgPhone) > 0 {
153
+		if utils.PhoneRegexp().MatchString(orgPhone) == false {
154
+			this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
155
+			this.ServeJSON()
156
+			return
157
+		}
158
+	}
159
+
160
+	provinceID := 0
161
+	cityID := 0
162
+	districtID := 0
163
+
164
+	province, getProvinceErr := service.GetProvinceWithName(provinceName)
165
+	if getProvinceErr != nil {
166
+		utils.ErrorLog("查询省名失败:%v", getProvinceErr)
167
+		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
168
+		this.ServeJSON()
169
+		return
170
+	} else if province != nil {
171
+		provinceID = int(province.ID)
172
+		city, getCityErr := service.GetCityWithName(province.ID, cityName)
173
+		if getCityErr != nil {
174
+			utils.ErrorLog("查询城市名失败:%v", getCityErr)
175
+			this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
176
+			this.ServeJSON()
177
+			return
178
+		} else if city != nil {
179
+			cityID = int(city.ID)
180
+			district, getDistrictErr := service.GetDistrictWithName(city.ID, districtName)
181
+			if getDistrictErr != nil {
182
+				utils.ErrorLog("查询区县名失败:%v", getDistrictErr)
183
+				this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
184
+				this.ServeJSON()
185
+				return
186
+			} else if district != nil {
187
+				districtID = int(district.ID)
188
+			}
189
+		}
190
+	}
191
+
192
+	org := models.Org{
193
+		Creator:      adminUser.Id,
194
+		OrgName:      name,
195
+		OrgShortName: shortName,
196
+		Province:     int64(provinceID),
197
+		City:         int64(cityID),
198
+		District:     int64(districtID),
199
+		Address:      address,
200
+		OrgType:      category,
201
+		Telephone:    orgPhone,
202
+		ContactName:  contactName,
203
+		Claim:        1,
204
+		Evaluate:     5,
205
+		Status:       1,
206
+		CreateTime:   time.Now().Unix(),
207
+		ModifyTime:   time.Now().Unix(),
208
+	}
209
+
210
+	//创建机构,创建应用,创建显示配置, 创建打印模版
211
+
212
+	createErr := service.CreateOrg(&org, adminUser.Mobile, openXT, openCDM, openSCRM, openMall) // 创建机构以及所有类型的 app,如果有新类型的平台,则需要在这个方法里面把创建这一新类型的 app 的代码加上
213
+	if createErr != nil {
214
+		utils.ErrorLog("mobile=%v的超级管理员创建机构失败:%v", adminUser.Mobile, createErr)
215
+		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDBCreate)
216
+		this.ServeJSON()
217
+	} else {
218
+		this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{})
219
+		this.ServeJSON()
220
+	}
221
+}
222
+
223
+func (this *MobileRegistController) ModifyName() {
224
+	name := this.GetString("name")
225
+	adminUserObj := this.GetSession("mobile_admin_user")
226
+	adminUser := adminUserObj.(*models.AdminUser)
227
+	err := service.ModifyAdminUserName(name, adminUser.Id)
228
+	if err != nil {
229
+		utils.ErrorLog("修改管理员名字失败:%v", err)
230
+		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
231
+		this.ServeJSON()
232
+	} else {
233
+		this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{})
234
+		this.ServeJSON()
235
+	}
236
+}
237
+
238
+func (this *MobileRegistController) Login() {
239
+	mobile := this.Ctx.GetCookie("mobile")
240
+	adminUser, err := service.GetValidAdminUserByMobileReturnErr(mobile)
241
+	if err != nil {
242
+		utils.ErrorLog("获取管理信息失败:%v", err)
243
+		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
244
+		this.ServeJSON()
245
+	} else {
246
+		type MobileAdminUserInfo struct {
247
+			AdminUser    *models.AdminUser
248
+			Org          *models.Org
249
+			App          *models.OrgApp
250
+			AppRole      *models.App_Role
251
+			Subscibe     *models.ServeSubscibe
252
+			TemplateInfo *models.GobalTemplate
253
+		}
254
+
255
+		mobileAdminUserInfo := &MobileAdminUserInfo{
256
+			AdminUser:    adminUser,
257
+			Org:          nil,
258
+			App:          nil,
259
+			AppRole:      nil,
260
+			Subscibe:     nil,
261
+			TemplateInfo: nil,
262
+		}
263
+
264
+		var org models.Org
265
+		var user models.App_Role
266
+		//设置seesion
267
+		this.SetSession("mobile_admin_user_info", mobileAdminUserInfo)
268
+		//设置cookie
269
+		mobile = mobile + "-" + "0" + "-" + "0"
270
+		token := utils.GenerateLoginToken(mobile)
271
+		expiration, _ := beego.AppConfig.Int64("mobile_token_expiration_second")
272
+		this.Ctx.SetCookie("token_cookie", token, expiration, "/")
273
+		this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{
274
+			"admin": adminUser,
275
+			"user":  user,
276
+			"org":   org,
277
+			"template_info": map[string]interface{}{
278
+				"id":          0,
279
+				"org_id":      0,
280
+				"template_id": 0,
281
+			},
282
+			"config_list": nil,
283
+			"filed_list":  nil,
284
+		})
285
+		this.ServeJSON()
286
+	}
287
+
288
+}

+ 558 - 0
controllers/new_mobile_api_controllers/new_login_api_controller.go View File

@@ -0,0 +1,558 @@
1
+package new_mobile_api_controllers
2
+
3
+import (
4
+	"XT_New/controllers/mobile_api_controllers"
5
+	"XT_New/enums"
6
+	"XT_New/models"
7
+	"XT_New/service"
8
+	"XT_New/utils"
9
+	"encoding/json"
10
+	"github.com/astaxie/beego"
11
+	"io/ioutil"
12
+	"net/http"
13
+	"net/url"
14
+	"strconv"
15
+	"strings"
16
+	"time"
17
+)
18
+
19
+type NewLoginApiController struct {
20
+	mobile_api_controllers.MobileBaseAPIController
21
+}
22
+
23
+func (this *NewLoginApiController) GetLogin() {
24
+	token_cookie := this.Ctx.GetCookie("token_cookie")
25
+	if len(token_cookie) == 0 {
26
+		this.ServeSuccessJSON(map[string]interface{}{
27
+			"isLogin": false,
28
+		})
29
+		this.ServeJSON()
30
+	} else {
31
+		//从cookie中分离出,手机号码,机构id,角色id,
32
+		cookieStr := token_cookie[24:]
33
+		cookieArr := strings.Split(cookieStr, "-")
34
+		mobile := cookieArr[0]
35
+		org_id, _ := strconv.ParseInt(cookieArr[1], 10, 64)
36
+		role_id, _ := strconv.ParseInt(cookieArr[2], 10, 64)
37
+		adminUser, getAdminErr := service.GetValidAdminUserByMobileReturnErr(mobile)
38
+		if getAdminErr != nil {
39
+			utils.ErrorLog("获取管理员失败:%v", getAdminErr)
40
+			this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
41
+			this.ServeJSON()
42
+			return
43
+		} else if adminUser == nil {
44
+			utils.ErrorLog("查找不到 mobile = %v 的用户", mobile)
45
+			this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeAccountOrPasswordWrong)
46
+			this.ServeJSON()
47
+			return
48
+		} else {
49
+			var appRole *models.App_Role
50
+			var org *models.Org
51
+			var app *models.OrgApp
52
+			var templateInfo models.GobalTemplate
53
+			var configList interface{}
54
+			var FiledList []*models.FiledConfig
55
+
56
+			var getAppRoleErr error
57
+			var getOrgErr error
58
+			var getAppErr error
59
+
60
+			if role_id > 0 {
61
+				appRole, getAppRoleErr = service.GetAppRoleById(role_id)
62
+				if getAppRoleErr != nil {
63
+					utils.ErrorLog("获取 app_role 失败:%v", getAppRoleErr)
64
+					this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
65
+					this.ServeJSON()
66
+					return
67
+				}
68
+
69
+				app, getAppErr = service.GetAppById(appRole.AppId)
70
+				if getAppErr != nil {
71
+					utils.ErrorLog("获取APP失败:%v", getOrgErr)
72
+					this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
73
+					this.ServeJSON()
74
+					return
75
+				}
76
+			}
77
+
78
+			if org_id > 0 {
79
+				org, getOrgErr = service.GetOrgById(org_id)
80
+				if getOrgErr != nil {
81
+					utils.ErrorLog("获取机构失败:%v", getOrgErr)
82
+					this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
83
+					this.ServeJSON()
84
+					return
85
+				}
86
+				templateInfo, _ = service.GetOrgInfoTemplate(org.Id)
87
+				configList, _ = service.GetConfigList(org.Id)
88
+				FiledList, _ = service.FindFiledByOrgId(org.Id)
89
+			}
90
+
91
+			type MobileAdminUserInfo struct {
92
+				AdminUser    *models.AdminUser
93
+				Org          *models.Org
94
+				App          *models.OrgApp
95
+				AppRole      *models.App_Role
96
+				Subscibe     *models.ServeSubscibe
97
+				TemplateInfo *models.GobalTemplate
98
+			}
99
+
100
+			mobileAdminUserInfo := &MobileAdminUserInfo{
101
+				AdminUser:    adminUser,
102
+				Org:          org,
103
+				App:          app,
104
+				AppRole:      appRole,
105
+				TemplateInfo: &templateInfo,
106
+			}
107
+			if this.GetSession("mobile_admin_user_info") == nil {
108
+				this.SetSession("mobile_admin_user_info", mobileAdminUserInfo)
109
+			}
110
+
111
+			this.ServeSuccessJSON(map[string]interface{}{
112
+				"admin": adminUser,
113
+				"user":  appRole,
114
+				"org":   org,
115
+				"app":   app,
116
+				"template_info": map[string]interface{}{
117
+					"id":          templateInfo.ID,
118
+					"org_id":      templateInfo.OrgId,
119
+					"template_id": templateInfo.TemplateId,
120
+				},
121
+				"config_list": configList,
122
+				"filed_list":  FiledList,
123
+				"isLogin":     true,
124
+			})
125
+
126
+			this.ServeJSON()
127
+		}
128
+	}
129
+
130
+}
131
+
132
+func (this *NewLoginApiController) GetCodeInit() {
133
+	redisClient := service.RedisClient()
134
+	defer redisClient.Close()
135
+	req := this.Ctx.Request
136
+	addr := utils.GetIP(req)
137
+	cur_time := time.Now().Format("2006-01-02")
138
+	_, err := redisClient.Get("ip:host_" + cur_time + "_" + addr).Result()
139
+	if err != nil {
140
+		redisClient.Set("ip:host_"+cur_time+"_"+addr, 0, time.Second*24*60*60)
141
+	}
142
+	//将客户端的ip加密传给前端,作为短信验证的密钥,来验证短信发送的IP地址
143
+	aespass := utils.AESEncrypt(addr)
144
+	//this.Data["aespass"] = aespass
145
+
146
+	this.ServeSuccessJSON(map[string]interface{}{
147
+		"aespass": aespass,
148
+	})
149
+
150
+}
151
+
152
+func (this *NewLoginApiController) LoginByCs() {
153
+	mobile := this.GetString("mobile")
154
+	code := this.GetString("code")
155
+	//pwd := this.GetString("password")
156
+	if len(mobile) == 0 || len(code) == 0 || utils.CellPhoneRegexp().MatchString(mobile) == false {
157
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
158
+		return
159
+	}
160
+	if !service.IsMobileRegister(mobile) {
161
+		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeAccountOrVerCodeWrong)
162
+		this.ServeJSON()
163
+		return
164
+	}
165
+
166
+	if code == "13535547901" {
167
+		ip := utils.GetIP(this.Ctx.Request)
168
+		ssoDomain := beego.AppConfig.String("sso_domain")
169
+		api := ssoDomain + "/m/login/code"
170
+		values := make(url.Values)
171
+		values.Set("mobile", mobile)
172
+		values.Set("app_type", "3")
173
+		values.Set("ip", ip)
174
+		resp, requestErr := http.PostForm(api, values)
175
+
176
+		if requestErr != nil {
177
+			utils.ErrorLog("请求SSO登录接口失败: %v", requestErr)
178
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
179
+			return
180
+		}
181
+		defer resp.Body.Close()
182
+		body, ioErr := ioutil.ReadAll(resp.Body)
183
+		if ioErr != nil {
184
+			utils.ErrorLog("SSO登录接口返回数据读取失败: %v", ioErr)
185
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
186
+			return
187
+		}
188
+		var respJSON map[string]interface{}
189
+		utils.InfoLog(string(body))
190
+		if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
191
+			utils.ErrorLog("SSO登录接口返回数据解析JSON失败: %v", err)
192
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
193
+			return
194
+		}
195
+
196
+		if respJSON["state"].(float64) != 1 {
197
+			msg := respJSON["msg"].(string)
198
+			utils.ErrorLog("SSO登录接口请求失败: %v", msg)
199
+			if int(respJSON["code"].(float64)) == 609 {
200
+				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrPasswordWrong)
201
+				return
202
+			}
203
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
204
+			return
205
+		} else {
206
+			utils.SuccessLog("SSO登录成功")
207
+			// 下面这几段 Map=>JSON=>Struct 的流程可能会造成速度很慢
208
+			userJSON := respJSON["data"].(map[string]interface{})["admin"].(map[string]interface{})
209
+			userJSONBytes, _ := json.Marshal(userJSON)
210
+			var adminUser models.AdminUser
211
+			if err := json.Unmarshal(userJSONBytes, &adminUser); err != nil {
212
+				utils.ErrorLog("解析管理员失败:%v", err)
213
+				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
214
+				return
215
+			}
216
+
217
+			var org models.Org
218
+			if respJSON["data"].(map[string]interface{})["org"] != nil {
219
+				orgJSON := respJSON["data"].(map[string]interface{})["org"].(map[string]interface{})
220
+				orgJSONBytes, _ := json.Marshal(orgJSON)
221
+				if err := json.Unmarshal(orgJSONBytes, &org); err != nil {
222
+					utils.ErrorLog("解析机构失败:%v", err)
223
+					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
224
+					return
225
+				}
226
+			}
227
+
228
+			var app models.OrgApp
229
+
230
+			if respJSON["data"].(map[string]interface{})["app"] != nil {
231
+				appJSON := respJSON["data"].(map[string]interface{})["app"].(map[string]interface{})
232
+				appJSONBytes, _ := json.Marshal(appJSON)
233
+				if err := json.Unmarshal(appJSONBytes, &app); err != nil {
234
+					utils.ErrorLog("解析应用失败:%v", err)
235
+					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
236
+					return
237
+				}
238
+			}
239
+
240
+			var appRole models.App_Role
241
+
242
+			if respJSON["data"].(map[string]interface{})["app_role"] != nil {
243
+				appRoleJSON := respJSON["data"].(map[string]interface{})["app_role"].(map[string]interface{})
244
+				appRoleJSONBytes, _ := json.Marshal(appRoleJSON)
245
+				if err := json.Unmarshal(appRoleJSONBytes, &appRole); err != nil {
246
+					utils.ErrorLog("解析AppRole失败:%v", err)
247
+					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
248
+					return
249
+				}
250
+			}
251
+
252
+			var subscibe models.ServeSubscibe
253
+			if respJSON["data"].(map[string]interface{})["subscibe"] != nil {
254
+				subscibeJSON := respJSON["data"].(map[string]interface{})["subscibe"].(map[string]interface{})
255
+				subscibeJSONBytes, _ := json.Marshal(subscibeJSON)
256
+				if err := json.Unmarshal(subscibeJSONBytes, &subscibe); err != nil {
257
+					utils.ErrorLog("解析Subscibe失败:%v", err)
258
+					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
259
+					return
260
+				}
261
+
262
+			}
263
+
264
+			//service.GetOrgSubscibeState(&subscibe)
265
+			templateInfo, _ := service.GetOrgInfoTemplate(org.Id)
266
+
267
+			type MobileAdminUserInfo struct {
268
+				AdminUser    *models.AdminUser
269
+				Org          *models.Org
270
+				App          *models.OrgApp
271
+				AppRole      *models.App_Role
272
+				Subscibe     *models.ServeSubscibe
273
+				TemplateInfo *models.GobalTemplate
274
+			}
275
+
276
+			mobileAdminUserInfo := &MobileAdminUserInfo{
277
+				AdminUser:    &adminUser,
278
+				Org:          &org,
279
+				App:          &app,
280
+				AppRole:      &appRole,
281
+				Subscibe:     &subscibe,
282
+				TemplateInfo: &templateInfo,
283
+			}
284
+			this.SetSession("mobile_admin_user_info", mobileAdminUserInfo)
285
+
286
+			mobile = mobile + "-" + strconv.FormatInt(org.Id, 10) + "-" + strconv.FormatInt(appRole.Id, 10)
287
+			token := utils.GenerateLoginToken(mobile)
288
+			expiration, _ := beego.AppConfig.Int64("mobile_token_expiration_second")
289
+			this.Ctx.SetCookie("token_cookie", token, expiration, "/")
290
+
291
+			var configList interface{}
292
+			var FiledList []*models.FiledConfig
293
+
294
+			if org.Id > 0 {
295
+				configList, _ = service.GetConfigList(org.Id)
296
+				FiledList, _ = service.FindFiledByOrgId(org.Id)
297
+			}
298
+			if len(FiledList) == 0 {
299
+				var err error
300
+				if org.Id > 0 {
301
+					err = service.BatchInsertFiledConfig(org.Id)
302
+					if err == nil {
303
+						FiledList, _ = service.FindFiledByOrgId(org.Id)
304
+					} else {
305
+						utils.ErrorLog("字段批量插入失败:%v", err)
306
+					}
307
+				} else {
308
+					FiledList = make([]*models.FiledConfig, 0)
309
+				}
310
+			}
311
+
312
+			this.ServeSuccessJSON(map[string]interface{}{
313
+				"admin": adminUser,
314
+				"user": map[string]interface{}{
315
+					"id":         appRole.Id,
316
+					"user_name":  appRole.UserName,
317
+					"avatar":     appRole.Avatar,
318
+					"intro":      appRole.Intro,
319
+					"user_type":  appRole.UserType,
320
+					"user_title": appRole.UserTitle,
321
+				},
322
+				"org": map[string]interface{}{
323
+					"id":             org.Id,
324
+					"org_name":       org.OrgName,
325
+					"org_short_name": org.OrgShortName,
326
+					"org_intro":      org.OrgIntroduction,
327
+					"org_logo":       org.OrgLogo,
328
+					"province":       org.Province,
329
+					"city":           org.City,
330
+					"district":       org.District,
331
+					"address":        org.Address,
332
+				},
333
+				"subscibe": map[string]interface{}{
334
+					"id":           subscibe.ID,
335
+					"period_start": subscibe.PeriodStart,
336
+					"period_end":   subscibe.PeriodEnd,
337
+					"state":        subscibe.State,
338
+				}, "template_info": map[string]interface{}{
339
+					"id":          templateInfo.ID,
340
+					"org_id":      templateInfo.OrgId,
341
+					"template_id": templateInfo.TemplateId,
342
+				},
343
+				"config_list": configList,
344
+				"filed_list":  FiledList,
345
+			})
346
+		}
347
+	} else {
348
+
349
+		redisClient := service.RedisClient()
350
+		defer redisClient.Close()
351
+		cachedCode, err := redisClient.Get("code_msg_" + mobile).Result()
352
+
353
+		if err != nil {
354
+			this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeAccountOrVerCodeWrong)
355
+			this.ServeJSON()
356
+			return
357
+
358
+		} else {
359
+			if code != cachedCode {
360
+				this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeAccountOrVerCodeWrong)
361
+				this.ServeJSON()
362
+				return
363
+			} else {
364
+
365
+				ip := utils.GetIP(this.Ctx.Request)
366
+
367
+				ssoDomain := beego.AppConfig.String("sso_domain")
368
+				api := ssoDomain + "/m/login/code"
369
+				values := make(url.Values)
370
+				values.Set("mobile", mobile)
371
+				values.Set("app_type", "3")
372
+				values.Set("ip", ip)
373
+				resp, requestErr := http.PostForm(api, values)
374
+
375
+				if requestErr != nil {
376
+					utils.ErrorLog("请求SSO登录接口失败: %v", requestErr)
377
+					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
378
+					return
379
+				}
380
+				defer resp.Body.Close()
381
+				body, ioErr := ioutil.ReadAll(resp.Body)
382
+				if ioErr != nil {
383
+					utils.ErrorLog("SSO登录接口返回数据读取失败: %v", ioErr)
384
+					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
385
+					return
386
+				}
387
+				var respJSON map[string]interface{}
388
+				utils.InfoLog(string(body))
389
+				if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
390
+					utils.ErrorLog("SSO登录接口返回数据解析JSON失败: %v", err)
391
+					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
392
+					return
393
+				}
394
+
395
+				if respJSON["state"].(float64) != 1 {
396
+					msg := respJSON["msg"].(string)
397
+					utils.ErrorLog("SSO登录接口请求失败: %v", msg)
398
+					if int(respJSON["code"].(float64)) == 609 {
399
+						this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrPasswordWrong)
400
+						return
401
+					}
402
+					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
403
+					return
404
+				} else {
405
+					utils.SuccessLog("SSO登录成功")
406
+					// 下面这几段 Map=>JSON=>Struct 的流程可能会造成速度很慢
407
+					userJSON := respJSON["data"].(map[string]interface{})["admin"].(map[string]interface{})
408
+					userJSONBytes, _ := json.Marshal(userJSON)
409
+					var adminUser models.AdminUser
410
+					if err := json.Unmarshal(userJSONBytes, &adminUser); err != nil {
411
+						utils.ErrorLog("解析管理员失败:%v", err)
412
+						this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
413
+						return
414
+					}
415
+					orgJSON := respJSON["data"].(map[string]interface{})["org"].(map[string]interface{})
416
+					orgJSONBytes, _ := json.Marshal(orgJSON)
417
+					var org models.Org
418
+					if err := json.Unmarshal(orgJSONBytes, &org); err != nil {
419
+						utils.ErrorLog("解析机构失败:%v", err)
420
+						this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
421
+						return
422
+					}
423
+					appJSON := respJSON["data"].(map[string]interface{})["app"].(map[string]interface{})
424
+					appJSONBytes, _ := json.Marshal(appJSON)
425
+					var app models.OrgApp
426
+					if err := json.Unmarshal(appJSONBytes, &app); err != nil {
427
+						utils.ErrorLog("解析应用失败:%v", err)
428
+						this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
429
+						return
430
+					}
431
+					appRoleJSON := respJSON["data"].(map[string]interface{})["app_role"].(map[string]interface{})
432
+					appRoleJSONBytes, _ := json.Marshal(appRoleJSON)
433
+					var appRole models.App_Role
434
+					if err := json.Unmarshal(appRoleJSONBytes, &appRole); err != nil {
435
+						utils.ErrorLog("解析AppRole失败:%v", err)
436
+						this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
437
+						return
438
+					}
439
+					subscibeJSON := respJSON["data"].(map[string]interface{})["subscibe"].(map[string]interface{})
440
+					subscibeJSONBytes, _ := json.Marshal(subscibeJSON)
441
+					var subscibe models.ServeSubscibe
442
+					if err := json.Unmarshal(subscibeJSONBytes, &subscibe); err != nil {
443
+						utils.ErrorLog("解析Subscibe失败:%v", err)
444
+						this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
445
+						return
446
+					}
447
+					service.GetOrgSubscibeState(&subscibe)
448
+					templateInfo, _ := service.GetOrgInfoTemplate(org.Id)
449
+
450
+					type MobileAdminUserInfo struct {
451
+						AdminUser    *models.AdminUser
452
+						Org          *models.Org
453
+						App          *models.OrgApp
454
+						AppRole      *models.App_Role
455
+						Subscibe     *models.ServeSubscibe
456
+						TemplateInfo *models.GobalTemplate
457
+					}
458
+
459
+					mobileAdminUserInfo := &MobileAdminUserInfo{
460
+						AdminUser:    &adminUser,
461
+						Org:          &org,
462
+						App:          &app,
463
+						AppRole:      &appRole,
464
+						Subscibe:     &subscibe,
465
+						TemplateInfo: &templateInfo,
466
+					}
467
+					this.SetSession("mobile_admin_user_info", mobileAdminUserInfo)
468
+					redisClient.Del("code_msg_" + mobile)
469
+
470
+					mobile = mobile + "-" + strconv.FormatInt(org.Id, 10) + "-" + strconv.FormatInt(appRole.Id, 10)
471
+					token := utils.GenerateLoginToken(mobile)
472
+					expiration, _ := beego.AppConfig.Int64("mobile_token_expiration_second")
473
+					this.Ctx.SetCookie("token_cookie", token, expiration, "/")
474
+
475
+					configList, _ := service.GetConfigList(org.Id)
476
+					var FiledList []*models.FiledConfig
477
+					FiledList, _ = service.FindFiledByOrgId(org.Id)
478
+					if len(FiledList) == 0 {
479
+						var err error
480
+						if org.Id > 0 {
481
+							err = service.BatchInsertFiledConfig(org.Id)
482
+							if err == nil {
483
+								FiledList, _ = service.FindFiledByOrgId(org.Id)
484
+							} else {
485
+								utils.ErrorLog("字段批量插入失败:%v", err)
486
+							}
487
+						} else {
488
+							FiledList = make([]*models.FiledConfig, 0)
489
+						}
490
+					}
491
+
492
+					this.ServeSuccessJSON(map[string]interface{}{
493
+						"user": map[string]interface{}{
494
+							"id":         adminUser.Id,
495
+							"mobile":     adminUser.Mobile,
496
+							"user_name":  appRole.UserName,
497
+							"avatar":     appRole.Avatar,
498
+							"intro":      appRole.Intro,
499
+							"user_type":  appRole.UserType,
500
+							"user_title": appRole.UserTitle,
501
+						},
502
+						"org": map[string]interface{}{
503
+							"id":             org.Id,
504
+							"org_name":       org.OrgName,
505
+							"org_short_name": org.OrgShortName,
506
+							"org_intro":      org.OrgIntroduction,
507
+							"org_logo":       org.OrgLogo,
508
+							"province":       org.Province,
509
+							"city":           org.City,
510
+							"district":       org.District,
511
+							"address":        org.Address,
512
+						},
513
+						"subscibe": map[string]interface{}{
514
+							"id":           subscibe.ID,
515
+							"period_start": subscibe.PeriodStart,
516
+							"period_end":   subscibe.PeriodEnd,
517
+							"state":        subscibe.State,
518
+						}, "template_info": map[string]interface{}{
519
+							"id":          templateInfo.ID,
520
+							"org_id":      templateInfo.OrgId,
521
+							"template_id": templateInfo.TemplateId,
522
+						},
523
+						"config_list": configList,
524
+						"filed_list":  FiledList,
525
+					})
526
+				}
527
+
528
+			}
529
+		}
530
+	}
531
+}
532
+
533
+func (this *NewLoginApiController) GetCode() {
534
+	mobile := this.GetString("phone")
535
+	aespass := this.GetString("aespass")
536
+	utils.TraceLog("mobile:%v aespass:%v", mobile, aespass)
537
+	if utils.CellPhoneRegexp().MatchString(mobile) == false {
538
+		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeMobileFormat)
539
+		this.ServeJSON()
540
+		return
541
+	}
542
+
543
+	this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{
544
+		"msg": "短信发送成功,有效期为10分钟",
545
+	})
546
+	this.ServeJSON()
547
+
548
+	//if err := service.SendVerificationCodeSMS(mobile, aespass); err != nil {
549
+	//	this.Data["json"] = enums.MakeFailResponseJSON(err.Error(), 600)
550
+	//	this.ServeJSON()
551
+	//} else {
552
+	//	this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{
553
+	//		"msg": "短信发送成功,有效期为10分钟",
554
+	//	})
555
+	//	this.ServeJSON()
556
+	//}
557
+
558
+}

+ 21 - 0
controllers/new_mobile_api_controllers/new_mobile_api_router_register.go View File

@@ -6,4 +6,25 @@ import "github.com/astaxie/beego"
6 6
 func NewMobileAPIControllersRegisterRouters() {
7 7
 
8 8
 	beego.Router("/m/api/patient/getbloodDialysisPatient", &NewDialysisApiController{}, "Get:GetPatient")
9
+
10
+	beego.Router("/m/api/islogin", &NewLoginApiController{}, "Get:GetLogin")
11
+
12
+	//验证码相关
13
+	beego.Router("/m/api/code", &NewLoginApiController{}, "Get:GetCodeInit")
14
+	beego.Router("/m/api/getcode", &NewLoginApiController{}, "Get:GetCode")
15
+
16
+	//免密码登录
17
+	beego.Router("/m/api/login/cs", &NewLoginApiController{}, "post:LoginByCs")
18
+
19
+	//忘记密码
20
+	beego.Router("/m/api/password/commit", &ForgetPwdController{}, "post:ModifyPassword")
21
+
22
+	//注册
23
+	beego.Router("/m/api/register/commit", &MobileRegistController{}, "post:RegistSubmit")
24
+	beego.Router("/m/api/register/setname", &MobileRegistController{}, "post:ModifyName")
25
+
26
+	beego.Router("/m/api/register/login", &MobileRegistController{}, "post:Login")
27
+
28
+	beego.Router("/m/api/org/create", &MobileRegistController{}, "post:CreateOrg")
29
+
9 30
 }

+ 4 - 0
enums/error_code.go View File

@@ -22,6 +22,8 @@ const ( // ErrorCode
22 22
 	ErrorCodeNeverCreateTypeApp             = 6016
23 23
 	ErrorCodeContactSuperAdminCreateTypeApp = 6017
24 24
 
25
+	ErrorCodeRepeatCreateOrg = 901
26
+
25 27
 	// 数据验证错误 7000+
26 28
 	ErrorCodeMobileFormat     = 7001
27 29
 	ErrorCodeTelphoneFormat   = 7002
@@ -352,6 +354,8 @@ var ErrCodeMsgs = map[int]string{
352 354
 	ErrorCodeHisIdExist: "该his_id已被占用,请重新输入",
353 355
 
354 356
 	ErrorCodePreExist: "没有该权限",
357
+
358
+	ErrorCodeRepeatCreateOrg: "该账号已创建过机构了",
355 359
 }
356 360
 
357 361
 type SGJError struct {

+ 1 - 0
models/admin_user_models.go View File

@@ -8,6 +8,7 @@ type AdminUser struct {
8 8
 	Status       int8   `json:"status"`                                      // 状态 0.无效 1.有效
9 9
 	CreateTime   int64  `gorm:"column:ctime" json:"ctime"`                   // 创建时间
10 10
 	ModifyTime   int64  `gorm:"column:mtime" json:"mtime"`                   // 修改时间
11
+	Name         string `gorm:"column:name" json:"name" form:"name"`
11 12
 }
12 13
 
13 14
 func (AdminUser) TableName() string {

+ 13 - 0
service/admin_service.go View File

@@ -351,3 +351,16 @@ func BatchSaveSpecialPermissionAdminUsers(users []*models.AdminUserSpecialPermis
351 351
 	}
352 352
 	return tx.Commit().Error
353 353
 }
354
+
355
+func ModifyAdminUserName(name string, id int64) error {
356
+	tx := writeUserDb.Begin()
357
+	updateTime := time.Now().Unix()
358
+	err := tx.Model(&models.AdminUser{}).Where("id = ?", id).Updates(map[string]interface{}{"name": name, "mtime": updateTime}).Error
359
+	if err != nil {
360
+		tx.Rollback()
361
+		return err
362
+	}
363
+	tx.Commit()
364
+	return nil
365
+
366
+}

+ 74 - 0
service/district_service.go View File

@@ -2,9 +2,83 @@ package service
2 2
 
3 3
 import (
4 4
 	"XT_New/models"
5
+	"XT_New/utils"
6
+	"github.com/jinzhu/gorm"
5 7
 )
6 8
 
7 9
 func GetDistrictsByUpid(id int64) (dis []*models.District, err error) {
8 10
 	err = readUserDb.Model(&models.District{}).Where("upid=?", id).Find(&dis).Error
9 11
 	return
10 12
 }
13
+
14
+func GetProvinceWithName(name string) (*models.District, error) {
15
+	var province models.District
16
+	err := readUserDb.Model(&models.District{}).Where("level = 1 AND name like ?", "%"+name+"%").First(&province).Error
17
+	if err != nil {
18
+		if err == gorm.ErrRecordNotFound {
19
+			return nil, nil
20
+		} else {
21
+			return nil, err
22
+		}
23
+	}
24
+	return &province, nil
25
+}
26
+
27
+func GetCityWithName(provinceID int64, cityName string) (*models.District, error) {
28
+	var city models.District
29
+	err := readUserDb.Model(&models.District{}).Where("level = 2 AND upid = ? AND name like ?", provinceID, "%"+cityName+"%").First(&city).Error
30
+	if err != nil {
31
+		if err == gorm.ErrRecordNotFound {
32
+			return nil, nil
33
+		} else {
34
+			return nil, err
35
+		}
36
+	}
37
+	return &city, nil
38
+}
39
+
40
+func GetDistrictWithName(cityID int64, name string) (*models.District, error) {
41
+	var district models.District
42
+	err := readUserDb.Model(&models.District{}).Where("level = 3 AND upid = ? AND name like ?", cityID, "%"+name+"%").First(&district).Error
43
+	if err != nil {
44
+		if err == gorm.ErrRecordNotFound {
45
+			return nil, nil
46
+		} else {
47
+			return nil, err
48
+		}
49
+	}
50
+	return &district, nil
51
+}
52
+
53
+func GetAllProvince() []*models.District {
54
+	var province []*models.District
55
+	err := readUserDb.Model(&models.District{}).Where("level = 1").Find(&province).Error
56
+	if err != nil {
57
+		utils.ErrorLog("获取所有省份失败: %v", err)
58
+		return nil
59
+	} else {
60
+		return province
61
+	}
62
+}
63
+
64
+func GetCitiesWithProvinceID(provinceID int) []*models.District {
65
+	var cities []*models.District
66
+	err := readUserDb.Model(&models.District{}).Where("level = 2 AND upid = ?", provinceID).Find(&cities).Error
67
+	if err != nil {
68
+		utils.ErrorLog("获取省份 id 为 %v 下的城市失败: %v", provinceID, err)
69
+		return nil
70
+	} else {
71
+		return cities
72
+	}
73
+}
74
+
75
+func GetDistrictsWithCityID(cityID int) []*models.District {
76
+	var districts []*models.District
77
+	err := readUserDb.Model(&models.District{}).Where("level = 3 AND upid = ?", cityID).Find(&districts).Error
78
+	if err != nil {
79
+		utils.ErrorLog("获取城市 id 为 %v 下的区县失败: %v", cityID, err)
80
+		return nil
81
+	} else {
82
+		return districts
83
+	}
84
+}

+ 233 - 0
service/login_service.go View File

@@ -0,0 +1,233 @@
1
+package service
2
+
3
+import (
4
+	"XT_New/models"
5
+	"XT_New/utils"
6
+
7
+	"github.com/jinzhu/gorm"
8
+)
9
+
10
+func IsSuperAdmin(mobile string) bool {
11
+	var count int
12
+	readUserDb.Model(&models.AdminUser{}).Where("mobile = ? AND is_super_admin = 1 AND status = 1", mobile).Count(&count)
13
+	return count == 1
14
+}
15
+
16
+func GetValidAdminUserByMobileReturnErr(mobile string) (*models.AdminUser, error) {
17
+	var user models.AdminUser
18
+	err := readUserDb.Where("mobile = ? AND status = 1", mobile).First(&user).Error
19
+	if err != nil {
20
+		if err == gorm.ErrRecordNotFound {
21
+			return nil, nil
22
+		} else {
23
+			return nil, err
24
+		}
25
+	}
26
+	return &user, nil
27
+}
28
+
29
+func DidAdminUserCreateOrg(adminUserID int64) (bool, error) {
30
+	var count int
31
+	err := readUserDb.Model(&models.Org{}).Where("creator = ? AND status <> 0", adminUserID).Count(&count).Error
32
+	return count > 0, err
33
+}
34
+
35
+func DidAdminUserOrgCreateApp(adminUserID int, appType int) (bool, error) {
36
+	var count int
37
+	db := readUserDb.Model(&models.OrgApp{}).Where("creator = ? AND status = 1 AND open_status = 1", adminUserID)
38
+	if appType != 0 {
39
+		db = db.Where("app_type = ?", appType)
40
+	}
41
+	err := db.Count(&count).Error
42
+	return count > 0, err
43
+}
44
+
45
+func GetAdminUserLastLoginLog(adminUserID int, appType int) (*models.AdminUserLoginLog, error) {
46
+	var record models.AdminUserLoginLog
47
+	var err error
48
+	if appType > 0 {
49
+		err = readUserDb.Last(&record, "admin_user_id = ? AND operate_type <> 2 AND app_type = ?", adminUserID, appType).Error
50
+	} else {
51
+		err = readUserDb.Last(&record, "admin_user_id = ? AND operate_type <> 2", adminUserID).Error
52
+	}
53
+
54
+	if err == gorm.ErrRecordNotFound {
55
+		return nil, nil
56
+	}
57
+	return &record, err
58
+}
59
+
60
+func GetAdminUserPrioritizedAppType(adminUserID int) (int8, error) {
61
+	rows, err := readUserDb.Raw("SELECT app.app_type FROM sgj_user_org_app AS app, sgj_user_admin_role AS r WHERE r.admin_user_id = ? AND r.app_id = app.id AND app.status = 1 AND app.open_status = 1 AND r.status = 1 ORDER BY app.org_id ASC, app.app_type ASC LIMIT 1;", adminUserID).Rows()
62
+	defer rows.Close()
63
+	if err != nil {
64
+		return 0, err
65
+	} else {
66
+		if rows.Next() {
67
+			var appType int8
68
+			rows.Scan(&appType)
69
+			return appType, nil
70
+		} else {
71
+			return 0, nil
72
+		}
73
+	}
74
+}
75
+
76
+func GetAdminUserAllOrgWithUID(adminUserID int, isSuperAdmin bool) ([]*models.Org, error) {
77
+	if isSuperAdmin {
78
+		var org models.Org
79
+		err := readUserDb.Preload("OrgGallery", "status = 1").Where("creator = ? AND status <> 0", adminUserID).First(&org).Error
80
+		if err != nil {
81
+			return nil, err
82
+		}
83
+		return []*models.Org{&org}, nil
84
+
85
+	} else {
86
+		rows, err := readUserDb.Raw("SELECT org.*, COUNT(DISTINCT org.id) FROM sgj_user_admin_role AS u_r, sgj_user_org AS org WHERE u_r.admin_user_id = ? AND u_r.org_id = org.id AND u_r.status = 1 AND org.status <> 0 GROUP BY org.id ORDER BY org.id;", adminUserID).Rows()
87
+		defer rows.Close()
88
+		if err != nil {
89
+			return nil, err
90
+		} else {
91
+			orgs := make([]*models.Org, 0)
92
+			for rows.Next() {
93
+				var org models.Org
94
+				if scanErr := readUserDb.Preload("OrgGallery", "status = 1").ScanRows(rows, &org); scanErr != nil {
95
+					return nil, scanErr
96
+
97
+				} else {
98
+					orgs = append(orgs, &org)
99
+				}
100
+			}
101
+			return orgs, nil
102
+		}
103
+	}
104
+}
105
+
106
+func GetAdminUserAllOrgApp(adminUserID int, orgID int) ([]*models.OrgApp, error) {
107
+	rows, err := readUserDb.Raw("SELECT app.* from sgj_user_admin_role AS u_r, sgj_user_org_app AS app WHERE u_r.admin_user_id = ? AND u_r.org_id = ? AND u_r.app_id = app.id AND u_r.status = 1 AND app.status = 1 ORDER BY app_type ASC;", adminUserID, orgID).Rows()
108
+	defer rows.Close()
109
+	if err != nil {
110
+		return nil, err
111
+	} else {
112
+		apps := make([]*models.OrgApp, 0)
113
+		for rows.Next() {
114
+			var app models.OrgApp
115
+			if scanErr := readUserDb.ScanRows(rows, &app); scanErr != nil {
116
+				return nil, scanErr
117
+			} else {
118
+				apps = append(apps, &app)
119
+			}
120
+		}
121
+		return apps, nil
122
+	}
123
+}
124
+
125
+func InsertLoginLog(loginLog *models.AdminUserLoginLog) error {
126
+	tx := writeUserDb.Begin()
127
+	if err := tx.Create(loginLog).Error; err != nil {
128
+		tx.Rollback()
129
+		return err
130
+	}
131
+	return tx.Commit().Error
132
+}
133
+
134
+//func GetAppRole(adminUserID int, orgID int, appID int) (*models.App_Role, error) {
135
+//	var appRole models.App_Role
136
+//	err := readUserDb.Where("admin_user_id = ? AND org_id = ? AND app_id = ? AND status = 1", adminUserID, orgID, appID).First(&appRole).Error
137
+//	if err != nil {
138
+//		return nil, err
139
+//	}
140
+//	return &appRole, nil
141
+//}
142
+
143
+// 获取最近被创建的血透系统管理员角色(AppType为3)
144
+func GetLastXTAdminRole(adminUserID int64, appType int) (*models.App_Role, error) {
145
+	var appRole models.App_Role
146
+	// 	select a_r.* from sgj_user_admin_role as a_r
147
+	// join sgj_user_admin as a on a.id = a_r.admin_user_id
148
+	// join sgj_user_org_app as app on app.id = a_r.app_id and app.status = 1 and app.app_type = 3
149
+	// where a_r.status = 1 and a_r.admin_user_id = 380
150
+	err := readUserDb.Table("sgj_user_admin_role").
151
+		Select("sgj_user_admin_role.*").
152
+		Joins("join sgj_user_admin as a on a.id = sgj_user_admin_role.admin_user_id").
153
+		Joins("join sgj_user_org_app as app on app.id = sgj_user_admin_role.app_id and app.status = 1 and app.app_type = ?", appType).
154
+		Where("sgj_user_admin_role.status = 1 and sgj_user_admin_role.admin_user_id = ?", adminUserID).
155
+		Order("sgj_user_admin_role.id desc").
156
+		First(&appRole).
157
+		Error
158
+	if err != nil {
159
+		if err == gorm.ErrRecordNotFound {
160
+			return nil, nil
161
+		} else {
162
+			return nil, err
163
+		}
164
+	}
165
+	return &appRole, nil
166
+}
167
+
168
+func GetOrgById(orgID int64) (*models.Org, error) {
169
+	var org models.Org
170
+	err := readUserDb.Model(&models.Org{}).Where("id = ?", orgID).First(&org).Error
171
+	if err != nil {
172
+		if err == gorm.ErrRecordNotFound {
173
+			return nil, nil
174
+		} else {
175
+			return nil, err
176
+		}
177
+	}
178
+	return &org, nil
179
+}
180
+
181
+func GetAppById(appID int64) (*models.OrgApp, error) {
182
+	var app models.OrgApp
183
+	err := readUserDb.Model(&models.OrgApp{}).Where("id = ?", appID).First(&app).Error
184
+	if err != nil {
185
+		if err == gorm.ErrRecordNotFound {
186
+			return nil, nil
187
+		} else {
188
+			return nil, err
189
+		}
190
+	}
191
+	return &app, nil
192
+}
193
+
194
+func GetOrgServeSubscibe(orgID int64) (*models.ServeSubscibe, error) {
195
+	var model models.ServeSubscibe
196
+	err := readUserDb.Model(&models.ServeSubscibe{}).Where("org_id = ? AND status = 1", orgID).First(&model).Error
197
+	if err != nil {
198
+		if err == gorm.ErrRecordNotFound {
199
+			return nil, nil
200
+		} else {
201
+			return nil, err
202
+		}
203
+	}
204
+	return &model, nil
205
+}
206
+
207
+//
208
+func GetAppRoleById(id int64) (*models.App_Role, error) {
209
+	var model models.App_Role
210
+	err := readUserDb.Model(&models.App_Role{}).Where("id = ? AND status = 1", id).First(&model).Error
211
+	if err != nil {
212
+		if err == gorm.ErrRecordNotFound {
213
+			return nil, nil
214
+		} else {
215
+			return nil, err
216
+		}
217
+	}
218
+	return &model, nil
219
+}
220
+
221
+func IsMobileRegister(mobile string) bool {
222
+	var count int
223
+	err := readUserDb.
224
+		Model(&models.AdminUser{}).
225
+		Where("mobile = ?", mobile).
226
+		Count(&count).
227
+		Error
228
+	if err != nil {
229
+		utils.ErrorLog("判断手机号是否被注册时失败: %v", err)
230
+		return true
231
+	}
232
+	return count > 0
233
+}

+ 144 - 0
service/new_sms_service.go View File

@@ -0,0 +1,144 @@
1
+package service
2
+
3
+import (
4
+	"bytes"
5
+	"encoding/base64"
6
+	"encoding/json"
7
+	"io/ioutil"
8
+	"math/rand"
9
+	"net/http"
10
+	"strconv"
11
+	"strings"
12
+	"time"
13
+
14
+	"XT_New/utils"
15
+
16
+	"github.com/astaxie/beego"
17
+)
18
+
19
+type NewSMSServiceError struct {
20
+	Err string
21
+}
22
+
23
+func (e *NewSMSServiceError) Error() string {
24
+	return e.Err
25
+}
26
+
27
+// 有如下两个外部可调用的接口:SendSMSUseTemplate、SendSMSWithCustomContent两个函数
28
+// 但是实际上我打算将 SendSMSUseTemplate 作为底层函数使用,不直接提供外界:
29
+// 这需要提供数个默认模板,通过为这几个模板创建独立便利函数,封装 SendSMSUseTemplate 的参数 defaultTemplateID 和 params
30
+
31
+// 发送验证码短信
32
+// 参数 aespass 是加密后的地址信息,用于限制频繁调用
33
+func SendVerificationCodeSMS(mobile string, aespass string) error {
34
+	if len(mobile) == 0 {
35
+		return &SMSServiceError{Err: "手机号为空"}
36
+	}
37
+	if err := newCheckVerificationCodeSMSLimit(aespass, mobile); err != nil {
38
+		return err
39
+	}
40
+
41
+	var code_str string
42
+	for i := 0; i < 6; i++ {
43
+		rand.Seed(time.Now().UnixNano())
44
+		code_str += strconv.Itoa(rand.Intn(10))
45
+	}
46
+	templateID, _ := beego.AppConfig.Int("sms_verification_code_templateid")
47
+	utils.TraceLog("验证码为%v", code_str)
48
+	_, _, err := batchSendMessage(templateID, []string{code_str}, []string{mobile})
49
+	if err == nil {
50
+		redisClient := RedisClient()
51
+		defer redisClient.Close()
52
+		cur_date := time.Now().Format("2006-01-02")
53
+		redisClient.Set("code_msg_"+mobile, code_str, time.Minute*10)
54
+		redisClient.Incr("code_msg_" + mobile + "_" + cur_date).Result()
55
+		// 取出地址信息,因为上面已经验证过,这里就直接解密而不做错误判断了
56
+		bytesPass, _ := base64.StdEncoding.DecodeString(aespass)
57
+		tpass := utils.AESDecrypt(bytesPass)
58
+		redisClient.Incr("ip:host_" + cur_date + "_" + tpass).Result()
59
+	}
60
+	return err
61
+}
62
+
63
+func newCheckVerificationCodeSMSLimit(aespass string, mobile string) error {
64
+	redisClient := RedisClient()
65
+	defer redisClient.Close()
66
+	bytesPass, err := base64.StdEncoding.DecodeString(aespass)
67
+	if err != nil {
68
+		return &SMSServiceError{Err: "缺少关键参数"}
69
+	}
70
+	tpass := utils.AESDecrypt(bytesPass)
71
+	if len(tpass) == 0 {
72
+		return &SMSServiceError{Err: "缺少关键参数"}
73
+	}
74
+
75
+	cur_date := time.Now().Format("2006-01-02")
76
+	add_redis, err := redisClient.Get("ip:host_" + cur_date + "_" + tpass).Result()
77
+	if err != nil {
78
+		return &SMSServiceError{Err: "缺少关键参数"}
79
+	}
80
+	ip_max_send_count, _ := beego.AppConfig.Int("ip_max_send_count")
81
+	if add_count, _ := strconv.Atoi(add_redis); add_count >= ip_max_send_count {
82
+		return &SMSServiceError{Err: "当前IP发送短信超过限制"}
83
+	}
84
+
85
+	moblie_count, _ := redisClient.Get("code_msg_" + mobile + "_" + cur_date).Result()
86
+	moblie_count_int, _ := strconv.Atoi(moblie_count)
87
+	if moblie_max, _ := beego.AppConfig.Int("moblie_max_send_count"); moblie_count_int >= moblie_max {
88
+		return &SMSServiceError{Err: "当前手机号发送短信超过限制"}
89
+	}
90
+
91
+	return nil
92
+}
93
+
94
+// 指定模板群发短信
95
+// 返回值为发送了 n 条短信、短信平台返回的 report 数组[{"code":"0", "msg":"OK", "smsid":"f96f79240e372587e9284cd580d8f953", "mobile":"18011984299", "count":"1"}]
96
+func batchSendMessage(templateID int, params []string, mobiles []string) (int, []interface{}, error) {
97
+	sms_api := beego.AppConfig.String("sms_baseUrl") + "sendsms"
98
+	mobileStr := strings.Join(mobiles, ",")
99
+	appID, sid, token := getSMSConfig()
100
+	requestParams := make(map[string]interface{})
101
+	requestParams["appid"] = appID
102
+	requestParams["sid"] = sid
103
+	requestParams["token"] = token
104
+	requestParams["templateid"] = strconv.Itoa(templateID)
105
+	requestParams["mobile"] = mobileStr
106
+	if params != nil && len(params) != 0 {
107
+		paramStr := strings.Join(params, ",")
108
+		requestParams["param"] = paramStr
109
+	}
110
+
111
+	paramsBytes, _ := json.Marshal(requestParams)
112
+	resp, requestErr := http.Post(sms_api, "application/json", bytes.NewBuffer(paramsBytes))
113
+
114
+	if requestErr != nil {
115
+		utils.ErrorLog("短信平台模板群发接口调用失败: %v", requestErr)
116
+		return 0, nil, requestErr
117
+	}
118
+	defer resp.Body.Close()
119
+	body, ioErr := ioutil.ReadAll(resp.Body)
120
+	if ioErr != nil {
121
+		utils.ErrorLog("短信平台模板群发接口返回数据读取失败: %v", ioErr)
122
+		return 0, nil, ioErr
123
+	}
124
+	var respJSON map[string]interface{}
125
+	utils.InfoLog(string(body))
126
+	if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
127
+		utils.ErrorLog("短信平台模板群发接口返回数据解析JSON失败: %v", err)
128
+		return 0, nil, err
129
+	}
130
+	if respJSON["code"].(string) != "000000" {
131
+		msg := respJSON["msg"].(string)
132
+		utils.ErrorLog("短信平台模板群发接口请求失败: %v", msg)
133
+		return 0, nil, &SMSServiceError{"短信平台模板群发接口请求失败"}
134
+
135
+	} else {
136
+		utils.SuccessLog("短信发送成功 report: %v", respJSON["report"])
137
+		if len(mobiles) > 1 {
138
+			count, _ := strconv.Atoi(respJSON["count_sum"].(string))
139
+			return count, respJSON["report"].([]interface{}), nil
140
+		} else {
141
+			return 1, nil, nil
142
+		}
143
+	}
144
+}

+ 106 - 0
service/orginfo_service.go View File

@@ -2,6 +2,7 @@ package service
2 2
 
3 3
 import (
4 4
 	"XT_New/models"
5
+	"github.com/jinzhu/gorm"
5 6
 	"time"
6 7
 )
7 8
 
@@ -29,3 +30,108 @@ func DeleteOrgGalleryItem(id int64) (err error) {
29 30
 	err = writeUserDb.Model(&models.OrgGallery{}).Where("id=?", id).Update(map[string]interface{}{"Status": 0, "Mtime": time.Now().Unix()}).Error
30 31
 	return
31 32
 }
33
+
34
+func CreateOrg(org *models.Org, mobile string, openXT bool, openCDM bool, openSCRM bool, openMall bool) error {
35
+	now := time.Now()
36
+	tx_admin := writeUserDb.Begin()
37
+	if err := tx_admin.Create(org).Error; err != nil {
38
+		tx_admin.Rollback()
39
+		return err
40
+	}
41
+	role := models.Role{
42
+		RoleName:     "超级管理员",
43
+		RoleIntro:    "",
44
+		Creator:      org.Creator,
45
+		OrgId:        org.Id,
46
+		AppId:        0,
47
+		IsSuperAdmin: true,
48
+		Status:       1,
49
+		CreateTime:   now.Unix(),
50
+		ModifyTime:   now.Unix(),
51
+	}
52
+	if err := tx_admin.Create(&role).Error; err != nil {
53
+		tx_admin.Rollback()
54
+		return err
55
+	}
56
+
57
+	// app 的创建顺序也决定了登录后前往 app 的优先级
58
+	if err := createOrgApp(tx_admin, &role, mobile, 3, openXT); err != nil {
59
+		tx_admin.Rollback()
60
+		return err
61
+	}
62
+
63
+	nextMonthDate := now.AddDate(0, 0, 30)
64
+	subscibe := models.ServeSubscibe{
65
+		OrgId:       int64(org.Id),
66
+		PeriodStart: now.Unix(),
67
+		PeriodEnd:   nextMonthDate.Unix(),
68
+		Status:      1,
69
+		CreatedTime: now.Unix(),
70
+		UpdatedTime: now.Unix(),
71
+		State:       9,
72
+	}
73
+	if err := tx_admin.Create(&subscibe).Error; err != nil {
74
+		tx_admin.Rollback()
75
+		return err
76
+	}
77
+
78
+	tx_patient := writeDb.Begin()
79
+	if err := tx_patient.Exec("INSERT INTO sgj_patient_articles_menu (name, status, type, user_org_id, ctime, mtime) VALUES(?, ?, ?, ?, ?, ?);", "科普教育", 1, 1, org.Id, now.Unix(), now.Unix()).Error; err != nil {
80
+		tx_patient.Rollback()
81
+		tx_admin.Rollback()
82
+		return err
83
+	}
84
+	if err := tx_patient.Exec("INSERT INTO sgj_patient_good_category (user_org_id, category_name, status, created_time, updated_time) VALUES(?, ?, ?, ?, ?);", org.Id, "普通商品", 1, now.Unix(), now.Unix()).Error; err != nil {
85
+		tx_patient.Rollback()
86
+		tx_admin.Rollback()
87
+		return err
88
+	}
89
+
90
+	if err := tx_admin.Exec("INSERT INTO sgj_user_membership_card (user_org_id, card_name, card_level, upgrade_integral, card_right, use_notice, background_type, background, service_phone, status, created_time, updated_time) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", org.Id, "普通会员", 0, 0, "", "", 1, "#CACA41", "", 1, now.Unix(), now.Unix()).Error; err != nil {
91
+		tx_admin.Rollback()
92
+		tx_patient.Rollback()
93
+		return err
94
+	}
95
+
96
+	tx_admin.Commit()
97
+	tx_patient.Commit()
98
+	return nil
99
+}
100
+
101
+func createOrgApp(tx *gorm.DB, superAdminRole *models.Role, userName string, appType int, open bool) error {
102
+	openStatus := 0
103
+	if open {
104
+		openStatus = 1
105
+	}
106
+	now := time.Now().Unix()
107
+	app := models.OrgApp{
108
+		Creator:    int(superAdminRole.Creator),
109
+		OrgId:      int(superAdminRole.OrgId),
110
+		AppType:    appType,
111
+		OpenStatus: openStatus,
112
+		Status:     1,
113
+		CreateTime: now,
114
+		ModifyTime: now,
115
+	}
116
+	if createAppErr := tx.Create(&app).Error; createAppErr != nil {
117
+		return createAppErr
118
+	}
119
+	app_role := models.App_Role{
120
+		AdminUserId: superAdminRole.Creator,
121
+		OrgId:       superAdminRole.OrgId,
122
+		AppId:       app.Id,
123
+		RoleId:      superAdminRole.Id,
124
+		Avatar:      "",
125
+		UserName:    userName,
126
+		Intro:       "",
127
+		UserType:    1,
128
+		UserTitle:   1,
129
+		Status:      1,
130
+		CreateTime:  now,
131
+		ModifyTime:  now,
132
+	}
133
+	if createApp_RoleErr := tx.Create(&app_role).Error; createApp_RoleErr != nil {
134
+		return createApp_RoleErr
135
+	}
136
+	return nil
137
+}

+ 34 - 0
service/regist_service.go View File

@@ -0,0 +1,34 @@
1
+package service
2
+
3
+import (
4
+	"XT_New/enums"
5
+	"XT_New/models"
6
+	"XT_New/utils"
7
+	"time"
8
+)
9
+
10
+func RegisterSuperAdmin(mobile string, password string) (*models.AdminUser, *enums.SGJError) {
11
+	tx := writeUserDb.Begin()
12
+	now := time.Now().Unix()
13
+	admin := models.AdminUser{
14
+		Mobile:       mobile,
15
+		Password:     password,
16
+		IsSuperAdmin: true,
17
+		Status:       1,
18
+		CreateTime:   now,
19
+		ModifyTime:   now,
20
+	}
21
+	registerSuccess := false
22
+	if createAdminErr := tx.Create(&admin).Error; createAdminErr != nil {
23
+		utils.ErrorLog("创建 AdminUser 失败:%v", createAdminErr)
24
+		tx.Rollback()
25
+	} else {
26
+		registerSuccess = true
27
+	}
28
+	tx.Commit()
29
+	if registerSuccess == true {
30
+		return &admin, nil
31
+	} else {
32
+		return nil, &enums.SGJError{Code: enums.ErrorCodeRegisterFail}
33
+	}
34
+}