Exemple #1
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)
}
Exemple #2
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
	}
}
Exemple #3
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))
}
Exemple #4
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)
}
Exemple #5
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)
}
Exemple #6
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)
}
Exemple #7
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")
	}
}
Exemple #8
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))
}
Exemple #9
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)
}
Exemple #10
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)
	}
}
Exemple #11
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)
	}
}
Exemple #12
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")
	}
}
Exemple #13
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)
}
Exemple #14
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)
}
Exemple #15
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)
	}
}
Exemple #16
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
}
Exemple #17
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()
}
Exemple #18
0
func validateSession(r render.Render, s sessions.Session) {
	isLogin := s.Get("IsLogin")

	if isLogin == nil {
		fmt.Println("Not login...")
		r.Redirect("/admin/login")
	}
}
Exemple #19
0
// sessionIsAlive checks that session cookie with label "user" exists and is valid.
func sessionIsAlive(session sessions.Session) bool {
	data := session.Get("user")
	_, exists := data.(int64)
	if exists {
		return true
	}
	return false
}
Exemple #20
0
func (s *AEServer) HandleLogout(session sessions.Session) {
	toki := session.Get("Login")
	if toki == nil {
		return
	}
	s.ch_logout <- toki.(string)
	session.Delete("Login")
}
Exemple #21
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))
}
Exemple #22
0
func RegisterHandler(session sessions.Session, r render.Render) {

	v := session.Get("username")
	if v == nil {
		r.Redirect("/")
	} else {
		r.HTML(200, "register", nil)
	}
}
Exemple #23
0
func unmarshallToken(s sessions.Session) (t *token) {
	if s.Get(keyToken) == nil {
		return
	}
	data := s.Get(keyToken).([]byte)
	var tk oauth.Token
	json.Unmarshal(data, &tk)
	return &token{tk}
}
Exemple #24
0
func (m *Messages) SetSession(session sessions.Session) {
	m.session = session

	sessionData := session.Get(SESSION_KEY)

	if sessionData != nil {
		json.Unmarshal([]byte(sessionData.(string)), m)
	}
}
Exemple #25
0
func Auth(session sessions.Session, c martini.Context, r render.Render) {
	v := session.Get("userid")
	fmt.Println(v)
	if v == nil {
		r.Redirect("/login")
	} else {
		c.Next()
	}
}
func ArchivesHandler(w http.ResponseWriter, req *http.Request, r render.Render, session sessions.Session) {
	username, ok := session.Get("username").(string)
	if ok && username != "" {
		r.HTML(200, "admin/archives", map[string]string{"username": username})
	} else {
		http.Redirect(w, req, "/login/archives", http.StatusFound)
	}

}
func unmarshalCredentials(s sessions.Session, key string) (*oauth.Credentials, error) {
	if s.Get(key) == nil {
		return nil, errors.New("No stored credentials.")
	}
	data := s.Get(key).([]byte)
	var c oauth.Credentials
	json.Unmarshal(data, &c)
	return &c, nil
}
Exemple #28
0
func getFlash(session sessions.Session, key string) string {
	value := session.Get(key)

	if value == nil {
		return ""
	} else {
		session.Delete(key)
		return value.(string)
	}
}
Exemple #29
0
func login(t *oauth.Transport, s sessions.Session, w http.ResponseWriter, r *http.Request) {
	next := extractPath(r.URL.Query().Get(keyNextPage))
	if s.Get(keyToken) == nil {
		// User is not logged in.
		http.Redirect(w, r, t.Config.AuthCodeURL(next), codeRedirect)
		return
	}
	// No need to login, redirect to the next page.
	http.Redirect(w, r, next, codeRedirect)
}
Exemple #30
0
//The authorize middleware will search the session for a username
//if it doesnt find it, it will redirect to login
func authorize(w http.ResponseWriter, r *http.Request, session sessions.Session, c martini.Context) {
	username := session.Get("username")
	if username == nil {
		http.Redirect(w, r, "/login", http.StatusFound)
	}
	//if we found the user, let's create a new user struct and map it into the request context
	user := &User{}
	user.Username = username.(string)
	c.Map(user)
}