Exemple #1
0
func GetCv(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	w.WriteHeader(200)
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	attrMap := request.GenerateBasicAttrMap(w, r)
	loginName := attrMap[request.LOGIN_NAME_KEY]
	go_lib.LogInfoln(request.GetRequestInfo(r))
	auth_code := r.FormValue(request.AUTH_CODE)
	go_lib.LogInfof("Getting CV by user '%s' with input '%s'...\n", loginName, auth_code)
	pass, err := request.VerifyAuthCode(auth_code)
	if err != nil {
		go_lib.LogErrorf("Occur error when verify auth code: %s\n", err)
		// w.WriteHeader(500)
		fmt.Fprintln(w, "Error: Something wrong when verify auth code!")
		return
	}
	if !pass {
		go_lib.LogWarnf("Unauthorized CV getting by user '%s' with input '%s'.\n", loginName, auth_code)
		// w.WriteHeader(401)
		fmt.Fprintln(w, "FAIL: Wrong authorization code.")
		return
	}
	cvContent, err := base.GetCvContent()
	if err != nil {
		go_lib.LogErrorf("Occur error when get cv content: %s.\n", err)
		// w.WriteHeader(500)
		fmt.Fprintln(w, "Error: Something wrong when get CV content!")
		return
	}
	fmt.Fprintln(w, cvContent)
	go_lib.LogInfof("The CV had taken by user '%s' with input '%s'.\n", loginName, auth_code)
}
Exemple #2
0
func VerifyAuthCode(authCode string) (bool, error) {
	if len(authCode) == 0 {
		return false, nil
	}
	currentAuthCode, err := GetCurrentAuthCode()
	var pass bool
	if err == nil {
		pass = (currentAuthCode == strings.TrimSpace(authCode))
	}
	if pass {
		go func() {
			var newAuthCode string
			for {
				newAuthCode = generateAuthCode()
				if newAuthCode != currentAuthCode {
					break
				}
			}
			if len(newAuthCode) > 0 {
				conn := dao.RedisPool.Get()
				defer conn.Close()
				err = pushAuthCode(newAuthCode, conn)
				if err != nil {
					go_lib.LogErrorf("New auth code pushing error: %s\n", err)
				}
			}
		}()
	}
	return pass, err
}
Exemple #3
0
func DeleteTempFile(delay time.Duration, filePath string) (err error) {
	time.Sleep(delay)
	err = os.Remove(filePath)
	if err != nil {
		go_lib.LogErrorf("Occur error when delete file '%s': %s\n", filePath, err)
	} else {
		go_lib.LogInfof("The file '%s' is deleted.\n", filePath, err)
	}
	return
}
Exemple #4
0
func pushResponse(bufrw *bufio.ReadWriter, authCode string) bool {
	_, err := bufrw.Write([]byte(authCode))
	if err == nil {
		err = bufrw.Flush()
	}
	if err != nil {
		go_lib.LogErrorf("PushAuthCodeError: %s\n", err)
		return false
	}
	return true
}
Exemple #5
0
func recordPageAccessInfo(pageName string, visitor string, number uint64) bool {
	var result bool
	done, err := statistics.AddPageAccessRecord(pageName, visitor, number)
	if err != nil {
		go_lib.LogErrorf("Adding page access record error: %s (pageName=%s, visitor=%s, number=%d)\n", err, pageName, visitor, number)
		result = false
	} else {
		result = done
	}
	return result
}
Exemple #6
0
func ClearPageAccessRecord(pageName string, visitor string) (bool, error) {
	if len(pageName) == 0 {
		return false, errors.New("The parameter named pageName is EMPTY!")
	}
	sign := getSignForPage(pageName)
	sign.Set()
	defer sign.Unset()
	parameterInfo := fmt.Sprintf("(pageName=%s, visitor=%s)", pageName, visitor)
	var result bool
	conn := dao.RedisPool.Get()
	defer conn.Close()
	value, err := dao.GetHash(dao.PAGE_ACCESS_RECORDS_KEY, pageName)
	if err != nil {
		return false, err
	}
	visitorAccessRecords, err := parseVisitorAccessRecords(value)
	if err != nil {
		go_lib.LogErrorf("Parsing visitor access records error: %s %s\n", err, parameterInfo)
	}
	if visitorAccessRecords != nil {
		_, ok := visitorAccessRecords[visitor]
		if ok {
			delete(visitorAccessRecords, visitor)
			literals, err := formatVisitorAccessRecords(visitorAccessRecords)
			if err != nil {
				go_lib.LogErrorf("Formating visitor access records error: %s %s\n", err, parameterInfo)
			} else {
				result, err = dao.SetHash(dao.PAGE_ACCESS_RECORDS_KEY, pageName, literals)
				if err != nil {
					return false, err
				}
			}
		}
	}
	if result {
		go_lib.LogInfof("The page access info has been cleared. %s\n", parameterInfo)
	} else {
		go_lib.LogWarnf("The page access info failed to clear. %s\n", parameterInfo)
	}
	return result, nil
}
Exemple #7
0
func init() {
	for name, rights := range userGroupMap {
		userGroup, err := GetUserGroup(name)
		if err != nil {
			go_lib.LogErrorf("Get User Group (name=%s) Error: %s\n", name, err)
			continue
		}
		if userGroup != nil {
			err = DeleteUserGroup(name)
			if err != nil {
				go_lib.LogErrorf("Delete User Group (name=%s) Error: %s\n", name, err)
				continue
			}
		}
		userGroup = &UserGroup{Name: name, Rights: rights}
		err = AddUserGroup(userGroup)
		if err != nil {
			go_lib.LogErrorf("Add User Group '%v' Error: %s\n", userGroup, err)
			continue
		}
	}
}
Exemple #8
0
func GetAuthCodeForAdmin(w http.ResponseWriter, r *http.Request) {
	hj, ok := w.(http.Hijacker)
	if !ok {
		errorMsg := "The Web Server does not support Hijacking! "
		http.Error(w, errorMsg, http.StatusInternalServerError)
		go_lib.LogErrorf(errorMsg)
		return
	}
	conn, bufrw, err := hj.Hijack()
	if err != nil {
		errorMsg := "Internal error!"
		http.Error(w, errorMsg, http.StatusInternalServerError)
		go_lib.LogErrorf(errorMsg+" Hijacking Error: %s\n", err)
		return
	}
	defer conn.Close()
	r.ParseForm()
	reqType := r.FormValue("type")
	go_lib.LogInfoln(request.GetRequestInfo(r))
	attrMap := request.GenerateBasicAttrMap(w, r)
	loginName := attrMap[request.LOGIN_NAME_KEY]
	groupName := attrMap[request.GROUP_NAME_KEY]
	parameterOutline := fmt.Sprintf("[loginName=%s, groupName=%s, reqType=%s]", loginName, groupName, reqType)
	if groupName != rights.ADMIN_USER_GROUP_NAME {
		errorMsg := "Authentication failed!"
		http.Error(w, errorMsg, http.StatusForbidden)
		go_lib.LogErrorf(errorMsg+" [auth code push handler] %s \n", parameterOutline)
		return
	}
	if reqType != "lp" {
		currentAuthCode, err := request.GetCurrentAuthCode()
		if err != nil {
			go_lib.LogErrorf("GetCurrentAuthCodeError: %s\n", err)
		}
		go_lib.LogInfof("Push current auth code '%s' %s \n", currentAuthCode, parameterOutline)
		done := pushResponse(bufrw, currentAuthCode)
		if !done {
			go_lib.LogErrorf("Pushing current auth code '%s' is failing! %s \n", currentAuthCode, parameterOutline)
		}
	} else {
		nacChan := make(chan string)
		triggerFunc := func(newAuthCode string) {
			nacChan <- newAuthCode
		}
		triggerId := fmt.Sprintf("long-polling|%s|%s|%d", loginName, groupName, time.Now().UnixNano())
		request.AddNewAuthCodeTrigger(triggerId, triggerFunc)
		defer request.DelNewAuthCodeTrigger(triggerId)
		newAuthCode := <-nacChan // wait for new auth code generating
		go_lib.LogInfof("Push new auth code '%s' %s \n", newAuthCode, parameterOutline)
		done := pushResponse(bufrw, newAuthCode)
		if !done {
			go_lib.LogErrorf("Pushing new auth code '%s' is failing! %s \n", newAuthCode, parameterOutline)
		}
	}
	defer go_lib.LogInfof("The auth code push handler will be close. %s \n", parameterOutline)
}
Exemple #9
0
func MatchString(args ...interface{}) bool {
	if len(args) < 2 {
		return false
	}
	target := args[0].(string)
	for _, v := range args[1:len(args)] {
		pattern := v.(string)
		pass, err := regexp.MatchString(pattern, target)
		if err != nil {
			go_lib.LogErrorf("RegexpMatchError (target=%s, pattern=%s): %s\n", target, pattern, err)
			return false
		}
		if !pass {
			return false
		}
	}
	return true
}
Exemple #10
0
func GetUserListForAdmin(w http.ResponseWriter, r *http.Request) {
	hj, ok := w.(http.Hijacker)
	if !ok {
		errorMsg := "The Web Server does not support Hijacking! "
		http.Error(w, errorMsg, http.StatusInternalServerError)
		go_lib.LogErrorf(errorMsg)
		return
	}
	conn, bufrw, err := hj.Hijack()
	if err != nil {
		errorMsg := "Internal error!"
		http.Error(w, errorMsg, http.StatusInternalServerError)
		go_lib.LogErrorf(errorMsg+" Hijacking Error: %s\n", err)
		return
	}
	defer conn.Close()
	r.ParseForm()
	go_lib.LogInfoln(request.GetRequestInfo(r))
	attrMap := request.GenerateBasicAttrMap(w, r)
	loginName := attrMap[request.LOGIN_NAME_KEY]
	groupName := attrMap[request.GROUP_NAME_KEY]
	parameterOutline := fmt.Sprintf("[loginName=%s, groupName=%s]", loginName, groupName)
	if groupName != rights.ADMIN_USER_GROUP_NAME {
		errorMsg := "Authentication failed!"
		http.Error(w, errorMsg, http.StatusForbidden)
		go_lib.LogErrorf(errorMsg+" [user list handler] %s \n", parameterOutline)
		return
	}
	var respBuffer bytes.Buffer
	users, err := rights.FindUser("*")
	if err != nil {
		go_lib.LogErrorf("FindUserError: %s\n", err)
	} else {
		b, err := json.Marshal(users)
		if err != nil {
			go_lib.LogErrorf("JsonMarshalError (source=%v): %s\n", users, err)
		} else {
			respBuffer.WriteString(string(b))
		}
	}
	resp := respBuffer.String()
	done := pushResponse(bufrw, resp)
	if !done {
		go_lib.LogErrorf("Pushing user list '%s' is failing! %s \n", resp, parameterOutline)
	}
}
Exemple #11
0
func Login(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	go_lib.LogInfoln(request.GetRequestInfo(r))
	attrMap := request.GenerateBasicAttrMap(w, r)
	loginName := attrMap[request.LOGIN_NAME_KEY]
	if r.Method == "GET" {
		token := request.GenerateToken(r, loginName)
		go_lib.LogInfof("Token: %v\n", token)
		request.SaveToken(token)
		attrMap := request.GenerateBasicAttrMap(w, r)
		attrMap[request.TOKEN_KEY] = token.Key
		hint := r.FormValue(request.HINT_KEY)
		if len(hint) > 0 {
			attrMap[request.HINT_KEY] = hint
		}
		t, err := template.ParseFiles(request.GeneratePagePath("login"), request.GeneratePagePath("common"))
		if err != nil {
			go_lib.LogErrorln("TemplateParseErr:", err)
		}
		err = t.ExecuteTemplate(w, "page", attrMap)
		if err != nil {
			go_lib.LogErrorln("PageWriteErr:", err)
		}
	} else {
		r.ParseForm()
		tokenKey := r.Form.Get(request.TOKEN_KEY)
		go_lib.LogInfoln("Token Key:", tokenKey)
		validToken := request.CheckToken(tokenKey)
		if !validToken {
			go_lib.LogWarnf("Invalid token key '%s' ! Ignore the login request.", tokenKey)
			r.Method = "GET"
			http.Redirect(w, r, r.URL.Path, http.StatusFound)
			return
		} else {
			request.RemoveToken(tokenKey)
		}
		loginName = template.HTMLEscapeString(r.Form.Get(request.LOGIN_NAME_KEY))
		go_lib.LogInfoln("login - loginName:", loginName)
		password := template.HTMLEscapeString(r.Form.Get(request.PASSWORD_KEY))
		go_lib.LogInfoln("login - password:"******"remember-me")
		go_lib.LogInfoln("login - remember-me:", rememberMe)
		validLogin, err := rights.VerifyUser(loginName, password)
		go_lib.LogInfoln("Verify user:"******"/"
		if err != nil {
			go_lib.LogErrorf("VerifyUserError (loginName=%s): %s\n", loginName, err)
			redirectPath = r.URL.Path
		} else {
			if validLogin {
				longTerm := len(rememberMe) == 0 || rememberMe != "y"
				_, err = session.NewSession(loginName, longTerm, w, r)
				if err != nil {
					go_lib.LogErrorf("SetSessionError (loginName=%s): %s\n", loginName, err)
				}
			} else {
				hint := "Wrong login name or password."
				redirectPath = request.AppendParameter(r.URL.Path, map[string]string{request.HINT_KEY: hint})
			}
		}
		go_lib.LogInfof("RPATH: %s\n", redirectPath)
		http.Redirect(w, r, redirectPath, http.StatusFound)
	}
}