Ejemplo n.º 1
0
func LoginHandler(w http.ResponseWriter, r *http.Request, session sessions.Session, log *log.Logger) string {
	c, err := config.ReadDefault("users.cfg")

	if err != nil {
		return "Can't login. Problems reading user and password."
	}

	username := r.FormValue("username")
	password := r.FormValue("password")

	allowedUsername, _ := c.RawStringDefault("user")
	allowedPassword, _ := c.RawStringDefault("password")

	if username == allowedUsername && password == allowedPassword {

		log.Print("User WAS logged in.")

		session.Set("username", username)
		session.Set("password", password)
		http.Redirect(w, r, "/home", http.StatusFound)
		return "OK"
	}

	log.Print("User wasn't logged in. User " + username + " and password " + password)

	http.Redirect(w, r, "/login", http.StatusFound)
	return "Username or password incorrect"
}
Ejemplo n.º 2
0
func SetupAdmin(args martini.Params, session sessions.Session, r render.Render) {
	form := &forms.SetupAdmin{}
	session.Set("setup", "true")

	genform := utils.GenerateForm(form, "/setup", "POST", nil)
	r.HTML(200, "setup", genform)
}
Ejemplo n.º 3
0
func loginWithNameAndPwd(r *http.Request, res http.ResponseWriter, params martini.Params, session sessions.Session, render render.Render, l *log.Logger) {
	err := r.ParseForm()
	if err != nil {
		l.Printf("ParseForm error: %v\n", err)
		render.HTML(200, "error", "登录失败!")
		return
	}

	username := r.PostFormValue("username")
	//password := r.PostFormValue("password")

	l.Printf("Start logging in, username = %s \n", username)
	//gitlabClient, err := gogitlab.NewGitlabByLogin(constant.GitLabHost, constant.GitLabApiPath, username, password)
	//if err != nil {
	//	l.Printf("Login error: %v\n", err)
	//	render.HTML(200, "error", "登录失败!")
	//	return
	//}
	//gitUser, err := gitlabClient.CurrentUser()
	//if err != nil {
	//	l.Printf("Get current error: %v\n", err)
	//	render.HTML(200, "error", "登录失败!")
	//	return
	//}
	uInfo := &UserInfo{}
	session.Set(constant.UserInfoKey, uInfo)
	render.HTML(200, "dashboard", uInfo)
}
Ejemplo n.º 4
0
func UserLogin(r *http.Request, db *sql.DB, s sessions.Session, rw http.ResponseWriter) (int, string) {
	var id string
	var pass string

	email, password := r.FormValue("email"), r.FormValue("password")
	err := db.QueryRow("select id, password from appuser where email=$1", email).Scan(&id, &pass)

	if err != nil || bcrypt.CompareHashAndPassword([]byte(pass), []byte(password)) != nil {
		//return 401, "Not Authorized. Buuuurn!"
		http.Redirect(rw, r, "/wrong", http.StatusFound)
	}

	//set the user id in the session
	s.Set("userId", id)

	//return user
	if returnUrl, ok := s.Get("returnUrl").(string); ok {
		s.Delete("returnUrl")
		http.Redirect(rw, r, returnUrl, http.StatusFound)
	} else {
		http.Redirect(rw, r, "/", http.StatusFound)
	}

	return 200, "User id is " + id
}
Ejemplo n.º 5
0
func inner_GET_authorize(c martini.Context, sess sessions.Session, r *http.Request, ar *osin.AuthorizeRequest) bool {
	var (
		identity = ActiveIdentity(c)
		source   = current_url(r)
		handler  martini.Handler
	)

	if identity != nil {
		ar.UserData = identity
		sess.Delete("flow")
		return true
	} else {
		sess.Set("flow", FlowState{
			Type:    AuthorizeFlow,
			Source:  source,
			StartAt: time.Now(),
		})

		if provider := r.URL.Query().Get("p"); provider == "" {
			handler = show_provider_chooser()
		} else {
			handler = redirect_to_provider(provider)
		}
	}

	c.Invoke(handler)
	return false
}
Ejemplo n.º 6
0
// ReadUser is a route which fetches user according to parameter "id" on API side and according to retrieved
// session cookie on frontend side.
// Returns user struct with all posts merged to object on API call. Frontend call will render user "home" page, "user/index.tmpl".
func ReadUser(req *http.Request, params martini.Params, res render.Render, s sessions.Session) {
	var user User
	switch Root(req) {
	case "api":
		id, err := strconv.Atoi(params["id"])
		if err != nil {
			log.Println(err)
			res.JSON(400, map[string]interface{}{"error": "The user ID could not be parsed from the request URL."})
			return
		}
		user.ID = int64(id)
		user, err := user.Get()
		if err != nil {
			log.Println(err)
			if err.Error() == "not found" {
				res.JSON(404, NotFound())
				return
			}
			res.JSON(500, map[string]interface{}{"error": "Internal server error"})
			return
		}
		res.JSON(200, user)
		return
	case "user":
		user, err := user.Session(s)
		if err != nil {
			log.Println(err)
			s.Set("user", -1)
			res.HTML(500, "error", err)
			return
		}
		res.HTML(200, "user/index", user)
		return
	}
}
Ejemplo n.º 7
0
func userSiginCheck(info SiginIfo, session sessions.Session) string {
	var result bool
	info.UserName, result = check.CheckUserName(info.UserName)
	if result != true {
		return "-1"
	}

	info.UserNumber, result = check.CheckNumber(info.UserNumber)
	if result != true {
		return "-2"
	}

	isSelected := model.CheckSelected(info.UserNumber)
	if isSelected == false {
		return "-3"
	}

	resultSigin := model.Sigin(info.UserName, info.UserNumber)
	if resultSigin != true {
		return "-4"
	} else {
		session.Set("user_name", info.UserName)
		session.Set("user_number", info.UserNumber)

		return "1"
	}
}
Ejemplo n.º 8
0
func Login(session sessions.Session, re render.Render, r *http.Request) {
	client_id := common.Config.OAuth2Client_ID

	letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

	b := make([]rune, 10)
	for i := range b {
		b[i] = letters[rand.Intn(len(letters))]
	}
	session.AddFlash(string(b), "state")

	redirectBack := r.URL.Query().Get("redirect_back")
	ref := r.Referer()

	if redirectBack == "true" && ref != "" {
		session.Set("redirect_to", ref)
	} else {
		session.Set("redirect_to", nil)
	}

	query := url.Values{}
	query.Set("client_id", client_id)
	query.Set("state", string(b))
	query.Set("scope", "repo")

	dest := url.URL{
		Scheme:   "https",
		Host:     "github.com",
		Path:     "/login/oauth/authorize",
		RawQuery: query.Encode(),
	}
	re.Redirect(dest.String())
}
Ejemplo n.º 9
0
func SearchPage(user common.User, session sessions.Session, r render.Render, req *http.Request) {
	src, err := handleSearch(req.URL.Query())

	if err != nil {
		r.Error(400)
	}

	status := common.GetCodeSourceStatus(src)

	id := rand.Int63()
	params := req.URL.Query()
	usr := params.Get("user")
	repo := params.Get("repo")
	session.Set(id, usr+"/"+repo)

	data := struct {
		common.User
		Pagename     string
		Theme        string
		SourceStatus string
		WS_ID        int64

		Source *common.CodeSource
	}{user, "search", "standard", string(status), id, src}

	r.HTML(200, "search", data)
}
Ejemplo n.º 10
0
// GetPollHandler attempts to find the requested poll and responds with a json representation
func GetPollHandler(w http.ResponseWriter, r *http.Request, s sessions.Session, params martini.Params, ctx pollr.ApplicationContext) {
	// If this is the first time we've seen this user
	// create a new voter entry for them in the table and
	// send them their voter id
	if s.Get("voterId") == nil {
		voter := pollr.NewVoter()
		ctx.CreateVoter(voter)
		s.Options(sessions.Options{
			Domain:   r.Host,
			Path:     "/",
			MaxAge:   0,
			HttpOnly: false,
			Secure:   false,
		})
		s.Set("voterId", voter.Id.Hex())
	}
	id := params["id"]
	poll, err := ctx.FindPoll(id)
	if err != nil {
		log.Print(err)
		http.Error(w, fmt.Sprintf("Poll %s not found", id), 404)
		return
	}
	JsonPollResponse(w, poll)
}
Ejemplo n.º 11
0
func (s *AEServer) HandleLogin(r *http.Request, params martini.Params, session sessions.Session) (int, string) {
	a := AuthFromJson(r.Body)
	if a == nil {
		time.Sleep(time.Second)
		return 404, Message("Login Failed")
	}

	sltr := StrResponse{}
	sltr.Arg = a.Username
	sltr.Resp = make(chan string)
	s.ch_getsalt <- sltr
	salt := <-sltr.Resp
	if salt == "" {
		return 401, Message("No login salt registered!")
	}

	user := s.FindUserByName(a.Username)
	salt_pass := DoHash(user.Password, salt)
	if salt_pass != a.Password {
		fmt.Println("Invalid password.")
		time.Sleep(time.Second)
		return http.StatusUnauthorized, Message("Invalid Username or Password.")
	}

	user.login = time.Now()
	tok := s.GetSessionToken()
	s.ch_login <- &Session{tok, user}
	session.Set("Login", tok)

	fmt.Println("Logged in!")
	return 200, Stringify(user)
}
Ejemplo n.º 12
0
func (api *dialogueApi) apiAuthorize(r *http.Request, session sessions.Session, rndr render.Render) {
	// check authorization headers
	username := r.Header.Get("X-Auth-User")
	token := r.Header.Get("X-Auth-Token")
	if username == "" || token == "" {
		e := ApiError{
			Error: "username and token must be present",
		}
		rndr.JSON(401, e)
		return
	}
	// verify token
	auth, err := api.rdb.GetAuthorization(username)
	if err != nil {
		e := ApiError{
			Error: fmt.Sprintf("error verifying token: %s", err),
		}
		rndr.JSON(401, e)
		return
	}
	if auth == nil || auth.Token != token {
		e := ApiError{
			Error: "invalid username/token",
		}
		rndr.JSON(401, e)
		return
	}
	// all is well, set session
	session.Set("username", username)
}
Ejemplo n.º 13
0
func Login(session sessions.Session, db *mgo.Database, r render.Render, req *http.Request, writer http.ResponseWriter) string {
	writer.Header().Set("Content-Type", "text/javascript")
	userid := req.FormValue("userid")
	callback := req.FormValue("callback")
	password := req.FormValue("password")
	fmt.Println("userid", userid)
	if userid == "" {
		return util.Jsonp(JsonRet{"login", 401, "请登录", "abc"}, callback)
	} else {
		result := bson.M{}
		err := db.C("auth_user").Find(bson.M{"id": userid}).One(&result)
		fmt.Println(password)
		fmt.Println(result)

		if err == nil {
			values := result
			if values["password"] == password {
				session.Set("userid", values["id"])
				session.Set("username", values["name"])
				values["password"] = nil
				items := []interface{}{}
				db.C("good_shares").Find(bson.M{"acc": userid}).All(&items)
				values["items"] = items
				fmt.Println("登录成功!")
				return util.Jsonp(JsonRet{"login", 200, "登录成功", values}, callback)

			} else {
				return util.Jsonp(JsonRet{"login", 401, "登录失败!密码错误!", nil}, callback)
			}
		} else {
			return util.Jsonp(JsonRet{"login", 401, "登录失败!用户名错误!", nil}, callback)
		}
	}
}
Ejemplo n.º 14
0
func LoginPost(lu forms.Login, session sessions.Session, r render.Render, dbh *db.Dbh) {
	errs := ValidateLogin(&lu)
	if len(errs) > 0 {
		log.Printf("errors: %+v\n", errs)
	}

	user := dbh.GetUserByEmail(lu.Email)

	match := auth.MatchPassword(lu.Password, user.Password, user.Salt)

	if match {
		sessionkey := SessionKey(user.Email, user.Password, user.Salt)

		session.Set("loggedin", "true")
		session.Set("uid", user.Id)
		session.Set("email", user.Email)
		session.Set("key", sessionkey)

		dbh.CreateSession(models.UserSession{UserId: user.Id, SessionKey: sessionkey, Active: true, Timestamp: time.Now().Unix()})

		r.Redirect(strings.Join([]string{utils.AppCfg.Url(), "albums"}, "/"), http.StatusFound)
		return
	}

	session.Set("flash", "Invalid Email or Password")

	r.Redirect(strings.Join([]string{utils.AppCfg.Url(), "login"}, "/"), http.StatusFound)
}
Ejemplo n.º 15
0
func Login(session sessions.Session, su models.User, r render.Render, p *models.Page) {

	// Check if we are already logged in
	if su.Id > 0 {
		r.Redirect(strings.Join([]string{utils.AppCfg.Url(), "albums"}, "/"), http.StatusFound)
		return
	}

	session.Set("loggedin", "false")

	// Init error holder
	errs := make(map[string]string)

	err_flash := session.Get("flash")
	if err_flash != nil {
		errs["flash"] = err_flash.(string)
		session.Set("flash", nil)
	}

	genform := utils.GenerateForm(&forms.Login{}, "/login", "POST", errs)

	p.SetUser(su)
	p.SetTitle("Login")
	p.Data = LoginVars{Form: genform}

	encoder.Render(p.Encoding, 200, "login", p, r)
}
Ejemplo n.º 16
0
// LtiProblemSets handles /lti/problem_set requests.
// It creates the user/course if necessary, creates a session,
// and redirects the user to the problem set picker UI URL.
func LtiProblemSets(w http.ResponseWriter, r *http.Request, tx *sql.Tx, form LTIRequest, render render.Render, session sessions.Session) {
	now := time.Now()

	// load the coarse
	if _, err := getUpdateCourse(tx, &form, now); err != nil {
		loggedHTTPErrorf(w, http.StatusInternalServerError, "db error: %v", err)
		return
	}

	// load the user
	user, err := getUpdateUser(tx, &form, now)
	if err != nil {
		loggedHTTPErrorf(w, http.StatusInternalServerError, "db error: %v", err)
		return
	}

	// sign the user in
	session.Set("id", user.ID)

	u := &url.URL{
		Path: "/",
		Fragment: fmt.Sprintf("/problem_sets/%s/%s",
			url.QueryEscape(form.OAuthConsumerKey),
			url.QueryEscape(form.LaunchPresentationReturnURL)),
	}

	log.Printf("problem set picker redirecting to %s", u.String())
	//http.Redirect(w, r, u.String(), http.StatusSeeOther)
	http.Redirect(w, r, "/v2/users/me/cookie", http.StatusSeeOther)
}
Ejemplo n.º 17
0
func AuthRequired(su models.User, session sessions.Session, res http.ResponseWriter, req *http.Request) {
	if su.Id > 0 {
		return
	}
	log.Println("Login Required")
	session.Set("flash", "Login Required")
	http.Redirect(res, req, strings.Join([]string{utils.AppCfg.Url(), "login"}, "/"), http.StatusFound)
}
Ejemplo n.º 18
0
func PostLogin(rw http.ResponseWriter, req *http.Request, db_ *mgo.Database, s sessions.Session) {
	user, pass := req.FormValue("email"), req.FormValue("password")
	id, err := LoginUser(db_, user, pass)
	if err != nil {
		fmt.Println(err)
		http.Redirect(rw, req, PAGE_LOGIN, http.StatusFound)
	}
	s.Set("userId", id.Hex())
	http.Redirect(rw, req, FUNC_HOME, http.StatusFound)
}
Ejemplo n.º 19
0
// POST /auth
func PostAuth(s sessions.Session, r render.Render, req *http.Request) {
	email := req.PostFormValue("email")
	password := req.PostFormValue("password")
	session_id, err := db.Auth(email, password)
	if err != nil {
		r.Error(401)
	} else {
		s.Set("user_session", session_id)
		r.Redirect("/")
	}
}
Ejemplo n.º 20
0
func GithubCallback(session sessions.Session, r *http.Request, re render.Render) {
	code, state := r.URL.Query().Get("code"), r.URL.Query().Get("state")
	client_id, client_secret := common.Config.OAuth2Client_ID, common.Config.OAuth2Client_Secret

	flashes := session.Flashes("state")
	if code == "" || state == "" || session == nil || len(flashes) == 0 || flashes[0].(string) != state {
		re.Redirect("/")
		return
	}

	client := &http.Client{}

	form := url.Values{}
	form.Add("code", code)
	form.Add("client_id", client_id)
	form.Add("client_secret", client_secret)

	req, _ := http.NewRequest("POST", "https://github.com/login/oauth/access_token/", strings.NewReader(form.Encode()))
	req.Header.Set("Accept", "application/json")

	resp, _ := client.Do(req)
	body, _ := ioutil.ReadAll(resp.Body)
	parse := map[string]interface{}{}
	json.Unmarshal([]byte(string(body)), &parse)

	token := parse["access_token"].(string)

	req, _ = http.NewRequest("GET", "https://api.github.com/user?access_token="+token, nil)

	resp, _ = client.Do(req)
	body, _ = ioutil.ReadAll(resp.Body)
	parse = map[string]interface{}{}
	json.Unmarshal([]byte(string(body)), &parse)

	username, id := parse["login"].(string), strconv.FormatFloat(parse["id"].(float64), 'f', -1, 64)

	if !common.UserExist(id) {
		common.NewUser(id)
	}

	session.Set("loggedin", true)
	session.Set("username", username)
	session.Set("id", id)
	session.Set("token", token)

	redirectTo := session.Get("redirect_to")
	if redirectTo != nil {
		re.Redirect(redirectTo.(string))
	} else {
		re.Redirect("/")
	}
	session.Set("redirect_to", nil)
}
Ejemplo n.º 21
0
func Login(r *http.Request, render render.Render, db *gorp.DbMap, s sessions.Session) {
	user := User{}
	email, password := r.FormValue("email"), r.FormValue("password")
	err := db.SelectOne(&user, "Select * from users where email=? ", email)
	//tmp_pass, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	//err := db.QueryRow("select id, password from users where email=$1", email).Scan(&userId, &dbPasswd)
	if err != nil || bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) != nil {
		render.HTML(400, "404", "")
	}
	s.Set("userId", user.Id)
	render.HTML(200, "dashboard", "")
}
Ejemplo n.º 22
0
func EnsureSessionVariables(s sessions.Session, t oauth2.Tokens) {
	userName := s.Get("userName")
	twitchId := s.Get("twitchId")
	if userName == nil || twitchId == nil {
		u, err := GetTwitchUser(t.Access())
		if err != nil {
			log.Fatal(err)
		}

		s.Set("userName", u.DisplayName)
		s.Set("twitchId", u.Id)
	}
}
Ejemplo n.º 23
0
// 登陆(获取授权令牌)
// @router /users/authentication [get]
func (this *Controller) Authentication(req *http.Request, session sessions.Session) (int, []byte) {
	req.ParseForm()
	fmt.Println("req传过来", req.Form)
	// 验证用户
	userData, err := this.model.Authentication(req.Form.Get("account"), req.Form.Get("password"))
	if err != nil {
		return this.Error(err.Error())
	}

	// 生成session
	session.Set("id", userData.Id)

	return this.Success(AuthenticationInfo(userData))
}
Ejemplo n.º 24
0
func PostLogin(req *http.Request, db *sql.DB, s sessions.Session) (int, string) {
	var id string

	email, password := req.FormValue("email"), req.FormValue("password")
	err := db.QueryRow("select id from users where email=$1 and password=$2", email, password).Scan(&id)

	if err != nil {
		return 401, "Unauthorized"
	}

	s.Set("userId", id)

	return 200, "User id is " + id
}
Ejemplo n.º 25
0
func RequireLogin(s sessions.Session, db *sql.DB, c martini.Context, ren render.Render, returnUrl string) {
	user := &User{}
	err := db.QueryRow("select name, email from appuser where id=$1", s.Get("userId")).Scan(&user.Name, &user.Email)

	s.Set("returnUrl", returnUrl)

	if err != nil {
		ren.Redirect("/login")
		return
	}

	//map user to the context
	c.Map(user)
}
Ejemplo n.º 26
0
func PostLogin(req *http.Request, dbmap *gorp.DbMap, s sessions.Session) (int, string) {
	var userId string

	email, password := req.FormValue("email"), req.FormValue("password")
	err := dbmap.SelectOne(&userId, "select id from users where email=$1 and password=$2", email, Md5(password))

	if err != nil {
		return 401, "Unauthorized"
	}

	s.Set("userId", userId)

	return 200, "User id is " + userId
}
Ejemplo n.º 27
0
// LtiProblem handles /lti/problem/:unique requests.
// It creates the user/course/assignment if necessary, creates a session,
// and redirects the user to the main UI URL.
func LtiProblemSet(w http.ResponseWriter, r *http.Request, tx *sql.Tx, form LTIRequest, params martini.Params, session sessions.Session) {
	unique := params["unique"]
	if unique == "" {
		loggedHTTPErrorf(w, http.StatusBadRequest, "malformed URL: missing unique ID for problem")
		return
	}
	if unique != url.QueryEscape(unique) {
		loggedHTTPErrorf(w, http.StatusBadRequest, "unique ID must be URL friendly: %s is escaped as %s", unique, url.QueryEscape(unique))
		return
	}

	now := time.Now()

	// load the problem set
	problemSet := new(ProblemSet)
	if err := meddler.QueryRow(tx, problemSet, `SELECT * FROM problem_sets WHERE unique_id = $1`, unique); err != nil {
		loggedHTTPDBNotFoundError(w, err)
		return
	}

	// load the course
	course, err := getUpdateCourse(tx, &form, now)
	if err != nil {
		loggedHTTPErrorf(w, http.StatusInternalServerError, "db error: %v", err)
		return
	}

	// load the user
	user, err := getUpdateUser(tx, &form, now)
	if err != nil {
		loggedHTTPErrorf(w, http.StatusInternalServerError, "db error: %v", err)
		return
	}

	// load the assignment
	asst, err := getUpdateAssignment(tx, &form, now, course, problemSet, user)
	if err != nil {
		loggedHTTPErrorf(w, http.StatusInternalServerError, "db error: %v", err)
		return
	}

	// sign the user in
	session.Set("id", user.ID)

	// redirect to the console
	//http.Redirect(w, r, fmt.Sprintf("/#/assignment/%d", asst.ID), http.StatusSeeOther)
	_ = asst
	http.Redirect(w, r, "/v2/users/me/cookie", http.StatusSeeOther)
}
Ejemplo n.º 28
0
func PostLogin(req *http.Request, db *sql.DB, s sessions.Session) (int, string) {
	var id string
	var pw string

	email, password := req.FormValue("email"), req.FormValue("password")
	err := db.QueryRow("select id, password from users where email=$1", email).Scan(&id, &pw)

	if err != nil || bcrypt.CompareHashAndPassword([]byte(pw), []byte(password)) != nil {
		return 401, "Unauthorized"
	}

	s.Set("userId", id)

	return 200, "User id is " + id
}
Ejemplo n.º 29
0
func handleOAuth2Callback(t *oauth.Transport, s sessions.Session, w http.ResponseWriter, r *http.Request) {
	next := extractPath(r.URL.Query().Get("state"))
	code := r.URL.Query().Get("code")
	tk, err := t.Exchange(code)
	if err != nil {
		// Pass the error message, or allow dev to provide its own
		// error handler.
		http.Redirect(w, r, PathError, codeRedirect)
		return
	}
	// Store the credentials in the session.
	val, _ := json.Marshal(tk)
	s.Set(keyToken, val)
	http.Redirect(w, r, next, codeRedirect)
}
Ejemplo n.º 30
0
func EnsureAuth(session sessions.Session, r render.Render, req *http.Request, c martini.Context) {
	id, ok := session.Get("id").(int64)
	if !ok || id == 0 {
		session.AddFlash("warning: You must login first!")
		session.Set("previous_url", req.RequestURI)
		r.Redirect("/signin")
	} else if ok {
		var user models.User
		err := utils.ORM.First(&user, id).Error
		if err != nil {
			r.Error(500)
			return
		}
		c.Map(user)
	}
}