Esempio n. 1
0
func GET_callback_AC(c martini.Context, sess sessions.Session) {
	flow := sess.Get("flow").(FlowState)

	c.Invoke(update_account)
	c.Invoke(activate_session)
	c.Invoke(redirect_to(flow.Source))
}
Esempio n. 2
0
func (api *dialogueApi) PostTopicsPosts(w http.ResponseWriter, r *http.Request, session sessions.Session, params martini.Params, rndr render.Render) {
	content := r.FormValue("content")
	topicId := params["topicId"]
	author := session.Get("username")
	// check for content
	if content == "" {
		e := ApiError{
			Error: "content must be specified",
		}
		rndr.JSON(500, e)
		return
	}
	// new post
	post := &dialogue.Post{
		Content: content,
		TopicId: topicId,
		Author:  author.(string),
	}
	if err := api.rdb.SavePost(post); err != nil {
		e := ApiError{
			Error: fmt.Sprintf("Error saving post: %s", err),
		}
		rndr.JSON(500, e)
		return
	}
	w.WriteHeader(204)
}
Esempio n. 3
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)
}
Esempio n. 4
0
func handleSubmission(req *http.Request, r render.Render, db *mgo.Database, session sessions.Session, backends []Backend) {
	template := make(map[string]string)
	template["contactUrl"] = os.Getenv("CONTACT_URL")
	template["contactValue"] = os.Getenv("CONTACT_VALUE")
	template["message"] = "Something went wrong :'("
	err := req.ParseForm()
	if err != nil {
		r.HTML(http.StatusBadRequest, "error", template)
	}
	user := session.Get("user").(string)
	err = userHasSubmitted(db, user)

	if err != nil {
		log.Println(err)
		r.HTML(http.StatusInternalServerError, "error", template)
	} else {
		submission := &Submission{
			Name:    req.PostForm.Get("name"),
			Address: req.PostForm.Get("address"),
			Email:   req.PostForm.Get("email"),
			Size:    req.PostForm.Get("size"),
		}
		for i := 0; i < len(backends); i++ {
			go backends[i](submission)
		}
		r.HTML(http.StatusOK, "success", nil)
	}
}
Esempio n. 5
0
func getSignin(s sessions.Session, w http.ResponseWriter, r *http.Request) {
	s.Delete("username")
	if !oauthEnabled() {
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}

	body, err := Asset("templates/signin.html")
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		log.Printf("ERROR: %s", err)
		return
	}

	tmpl, err := template.New("config.js").Parse(string(body))
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		log.Printf("ERROR: %s", err)
		return
	}

	err = tmpl.Execute(w, struct {
		Error  string
		Google bool
	}{
		Error:  r.FormValue("error"),
		Google: googleOauthEnabled(),
	})
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		log.Printf("ERROR: %s", err)
		return
	}
}
Esempio n. 6
0
func (s *AEServer) HandlePostQuestion(w http.ResponseWriter, r *http.Request, session sessions.Session) (int, string) {
	//Verify user account or something
	login := session.Get("Login")
	if login == nil {
		return 404, Message("Not Logged In!")
	}
	tok := login.(string)
	user := s.syncGetUser(tok)
	if user == nil {
		return http.StatusBadRequest, Message("Invalid Cookie!")
	}

	q := QuestionFromJson(r.Body)
	if q == nil {
		return 404, Message("Poorly Formatted JSON.")
	}
	//Assign question an ID
	q.ID = bson.NewObjectId()
	q.Author = user.Username
	q.Timestamp = time.Now()

	err := s.questions.Save(q)
	if err != nil {
		log.Print(err)
		return http.StatusInternalServerError, Message("Failed to save question")
	}
	return 200, q.GetIdHex()
}
Esempio n. 7
0
func (mgr *Manager) authMidware(c martini.Context, w http.ResponseWriter, r *http.Request, ss sessions.Session) {
	if !strings.HasPrefix(r.URL.Path, API_PREFIX) {
		return
	}

	if !mgr.authRequired(r) {
		return
	}

	uid_ := ss.Get("uid")
	if uid_ == nil {
		w.WriteHeader(403)
		return
	}
	uid, ok := uid_.(int)
	if !ok {
		w.WriteHeader(403)
		return
	}

	exists := 0
	mgr.db.QueryRow("select 1 from admins where id == ?", uid).Scan(&exists)
	if exists == 1 {
		return
	}
	w.WriteHeader(403)
}
Esempio n. 8
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)
}
Esempio n. 9
0
/* Handle requests to vote in a poll
Expects the following json request.
{
	choiceId: 0
}
Response: json response of the created poll
*/
func PollVoteHandler(w http.ResponseWriter, r *http.Request, s sessions.Session,
	params martini.Params, ctx pollr.ApplicationContext) {
	// Find the requested poll and return a 404 if not found
	voterId := s.Get("voterId")
	if voterId == nil {
		fmt.Println("Can't find voterId!")
		http.Error(w, "Cheater", 404)
		return
	}
	poll, err := ctx.FindPoll(params["id"])
	if err != nil {
		log.Printf("Poll %s not found", params["id"])
		http.Error(w, "Poll not found", 404)
		return
	}
	// Decode the json request body to find the choiceId
	votePollEvent := &VotePollEvent{}
	if err := json.NewDecoder(r.Body).Decode(&votePollEvent); err != nil {
		fmt.Printf("VOTE: ERROR DECODING VOTEPOLLEVENT %s", r.Body)
		http.Error(w, "Bad vote data", 404)
		return
	}
	if votePollEvent.ChoiceId > uint(len(poll.Choices)) {
		fmt.Println("VOTE: ERROR CHOICEID OUT OF RANGE")
		http.Error(w, "Bad vote data", 404)
		return
	}
	ctx.Vote(voterId.(string), params["id"], votePollEvent.ChoiceId)
}
Esempio n. 10
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)
}
Esempio n. 11
0
func Index(session sessions.Session, r render.Render, auth core.AuthData) {

	var session_data = struct {
		Username  string
		PostsData Posts
	}{}

	v := session.Get("username")

	if v != nil {
		session_data.Username = v.(string)
	}

	req, _ := http.NewRequest("GET", "http://foojr.com/blog/posts", nil) //XXX handle error
	resp, _ := auth.CheckRequest(req)

	defer resp.Body.Close()
	data, _ := ioutil.ReadAll(resp.Body) //XXX handle error

	var posts Posts
	json.Unmarshal(data, &posts) //XXX handle error
	session_data.PostsData = posts

	r.HTML(200, "index", session_data)
}
Esempio n. 12
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"
}
Esempio n. 13
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)
}
Esempio n. 14
0
func GET_callback_BB(c martini.Context, sess sessions.Session) {
	flow := sess.Get("flow").(FlowState)

	c.Invoke(match_session_identity_with_flow)
	c.Invoke(create_account)
	c.Invoke(redirect_to(flow.Source))
}
Esempio n. 15
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
	}
}
Esempio n. 16
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)
		}
	}
}
Esempio n. 17
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)
}
Esempio n. 18
0
func DoLogin(entity models.UserLogin, session sessions.Session, enc Encoder, db gorp.SqlExecutor) (int, string) {

	status := &models.DefaultStruct{
		Id:       http.StatusForbidden,
		Name:     messages.GetLocaleMessage("en", "MSG_LOGIN_INVALID"),
		Lang_key: "en",
	}

	user := GetUserByLogin(entity, db)

	if user.Name != "" {

		err := sessionauth.AuthenticateSession(session, user)
		if err != nil {
			status.Name = messages.GetLocaleMessage("en", "MSG_SESSION_INIT_ERROR")
			return http.StatusForbidden, Must(enc.EncodeOne(status))
		}
		user.Authenticated = true
		user.UpdateLastLogin()
		status.Name = messages.GetLocaleMessage("en", "MSG_SUCCESSFUL_LOGIN")
		return http.StatusOK, Must(enc.EncodeOne(user))

	} else {

		sessionauth.Logout(session, user)
		session.Clear()
		return http.StatusForbidden, Must(enc.EncodeOne(status))

	}

	return http.StatusForbidden, Must(enc.EncodeOne(status))
}
Esempio n. 19
0
func UserGet(ren render.Render, params martini.Params, dbmap *gorp.DbMap, s sessions.Session) {
	var usr User
	log.Println(params)
	err := dbmap.SelectOne(&usr, "SELECT * from users WHERE id = $1", s.Get("userId"))
	PanicIf(err)
	ren.JSON(200, usr)
}
Esempio n. 20
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)
}
Esempio n. 21
0
func awardUser(db *mgo.Database, session sessions.Session, r render.Render, x csrf.CSRF) {
	template := make(map[string]string)
	template["contactUrl"] = os.Getenv("CONTACT_URL")
	template["contactValue"] = os.Getenv("CONTACT_VALUE")
	user := session.Get("user").(string)
	status := checkStatus(db, user)
	if status == 0 {
		template["message"] = "Can't seem to find records of you :/"
		r.HTML(http.StatusUnauthorized, "error", template)
	} else if status == 1 {
		err := userHasAuth(db, user)
		if err != nil {
			log.Println(err)
			template["message"] = "Uh oh! Please report this :("
			r.HTML(http.StatusInternalServerError, "error", template)
		} else {
			r.HTML(http.StatusOK, "form", x.GetToken())
		}
	} else if status == 2 {
		r.HTML(http.StatusOK, "form", x.GetToken())
	} else if status == 3 {
		template["message"] = "Hey buddy, it seems you have been awarded before."
		r.HTML(http.StatusUnauthorized, "error", template)
	}
}
Esempio n. 22
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)
}
Esempio n. 23
0
func PreventReauth(session sessions.Session, r render.Render) {
	_, ok := session.Get("id").(int64)
	if ok {
		session.AddFlash("warning: You are already signed in!")
		r.Redirect("/dashboard")
	}
}
Esempio n. 24
0
// Handler to require a user to log in. If the user is currently logged in
// nothing happens. Otherwise clear existing session and redirect the user
// to the login page
func RequireLogin(s sessions.Session, r render.Render) {
	session := s.Get("user_session")
	if session == nil {
		s.Clear()
		r.Redirect("/login")
	}
}
Esempio n. 25
0
func Check(w http.ResponseWriter, r *http.Request, sess sessions.Session) {
	auth := sess.Get("auth")
	if auth == nil {
		http.Redirect(w, r, "/admin/auth", http.StatusFound)
		return
	}
}
Esempio n. 26
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
}
Esempio n. 27
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"
	}
}
Esempio n. 28
0
func userInforEdit(session sessions.Session, r render.Render) {
	user_number := session.Get("user_number")
	user_name := session.Get("user_name")
	if user_number == nil || user_name == nil {
		r.HTML(200, "home", nil)
	}
	var name string
	var number string
	if value, ok := user_name.(string); ok {
		name = value
	} else {
		r.HTML(200, "home", nil)
	}

	if value, ok := user_number.(string); ok {
		number = value
	} else {
		r.HTML(200, "home", nil)
	}

	var user model.User
	user, err := model.GetUserInfo(name, number)
	if err != true {
		r.HTML(200, "home", nil)
	} else {
		r.HTML(200, "userInforEdit", user)
	}
}
Esempio n. 29
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)
}
Esempio n. 30
0
func (u UserHandler) Profile(session sessions.Session, user sessionauth.User, params martini.Params, r render.Render) {
	//fmt.Printf("Profile session: %v\n", session)
	//fmt.Printf("Profile params: %v\n", params)
	fmt.Printf("Profile user: %v\n", user.(*model.UserModel))
	fmt.Printf("Profile , AUTHUNIQUEID:%v \n", session.Get("AUTHUNIQUEID"))
	//fmt.Printf("Profile , id:%v \n", session.Get("id"))
	r.HTML(200, "user/profile", user.(*model.UserModel))
}