Example #1
0
func postLogin(w http.ResponseWriter, r *http.Request, c *web.Context) {
	email, password := r.FormValue("email"), r.FormValue("password")
	user, ok := GetUser(email, password)
	if !ok || (user.Role != "employee" && user.Role != "admin") {
		c.SetFlash("alertError", "Incorrect email or password")
		http.Redirect(w, r, "/login", 303)
		return
	}
	employee, ok := GetEmployee(user.Id)
	if !ok {
		c.SetFlash("alertError", "Error finding user")
		http.Redirect(w, r, "/login", 303)
		return
	}
	c.Login(user.Role)
	c.SetSession(map[string]interface{}{
		"emplyeeId": employee.Id,
		"email":     employee.Email,
	})
	if user.Role == "employee" {
		http.Redirect(w, r, "/employee/home", 303)
		return
	}
	if user.Role == "admin" {
		http.Redirect(w, r, "/admin/home", 303)
		return
	}
	return
}
Example #2
0
// Processes for data for signup and sends email to verify account
func DoSignup(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	vKey := make([]byte, 32)
	n, err := rand.Read(vKey)
	if n != len(vKey) || err != nil {
		log.Println("Could not successfully read from the system CSPRNG.")
	}
	validationKey := hex.EncodeToString(vKey)
	stmt, _ := db.Prepare("insert into signup(username, email, password, validationKey) values(?,?,?,?)")
	_, err = stmt.Exec(r.FormValue("username"), r.FormValue("email"), r.FormValue("password"), validationKey)
	if err != nil {
		// if a validation requests already exists resend email
		if strings.Contains(err.Error(), "1062") {
			log.Println("1062 error")
			stmt, _ := db.Prepare("select validationKey from signup where username=?")
			res := stmt.QueryRow(r.FormValue("username"))
			res.Scan(&validationKey)
			sendVerification(r.FormValue("email"), validationKey)
			http.Redirect(w, r, r.URL.Host+"/resendValidation", 302)
		} else {
			log.Print("Error creating signup record")
			log.Println(err)
		}
	} else {
		sendVerification(r.FormValue("email"), validationKey)
		http.Redirect(w, r, r.URL.Host+"/validationSent", 302)
	}
}
Example #3
0
File: goa.go Project: alytvynov/goa
func (h handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	if session.Store == nil {
		// server should not be started until Store is set!
		panic(session.ErrNoStore)
	}
	// login page should be allowed
	if req.URL.Path == LoginPage {
		h.Handler.ServeHTTP(rw, req)
		return
	}
	// check the cookie existance
	s, err := session.Store.Get(req)
	if err != nil {
		http.Redirect(rw, req, LoginPage+"?from="+url.QueryEscape(req.URL.String()), http.StatusFound)
		return
	}
	// check for cookie expiration
	if s.Expires.Before(time.Now()) {
		if err = session.Store.Del(req, rw); err != nil {
			http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
		http.Redirect(rw, req, LoginPage+"?from="+url.QueryEscape(req.URL.String()), http.StatusTemporaryRedirect)
		return
	}
	// refresh expiration and store new cookie
	s.Expires = time.Now().Add(session.MaxAge)
	session.Store.Put(req, rw, *s)
	h.Handler.ServeHTTP(rw, req)
}
Example #4
0
func login(c *api.Context, w http.ResponseWriter, r *http.Request) {
	if !CheckBrowserCompatability(c, r) {
		return
	}
	params := mux.Vars(r)
	teamName := params["team"]

	var team *model.Team
	if tResult := <-api.Srv.Store.Team().GetByName(teamName); tResult.Err != nil {
		l4g.Error("Couldn't find team name=%v, teamURL=%v, err=%v", teamName, c.GetTeamURL(), tResult.Err.Message)
		http.Redirect(w, r, api.GetProtocol(r)+"://"+r.Host, http.StatusTemporaryRedirect)
		return
	} else {
		team = tResult.Data.(*model.Team)
	}

	// If we are already logged into this team then go to home
	if len(c.Session.UserId) != 0 && c.Session.TeamId == team.Id {
		page := NewHtmlTemplatePage("home", "Home")
		page.Props["TeamURL"] = c.GetTeamURL()
		page.Render(c, w)
		return
	}

	// We still might be able to switch to this team because we've logged in before
	if multiCookie, err := r.Cookie(model.MULTI_SESSION_TOKEN); err == nil {
		multiToken := multiCookie.Value

		if len(multiToken) > 0 {
			tokens := strings.Split(multiToken, " ")

			for _, token := range tokens {
				if sr := <-api.Srv.Store.Session().Get(token); sr.Err == nil {
					s := sr.Data.(*model.Session)

					if !s.IsExpired() && s.TeamId == team.Id {
						w.Header().Set(model.HEADER_TOKEN, s.Token)
						sessionCookie := &http.Cookie{
							Name:     model.SESSION_TOKEN,
							Value:    s.Token,
							Path:     "/",
							MaxAge:   model.SESSION_TIME_WEB_IN_SECS,
							HttpOnly: true,
						}

						http.SetCookie(w, sessionCookie)

						http.Redirect(w, r, c.GetSiteURL()+"/"+team.Name+"/channels/town-square", http.StatusTemporaryRedirect)
						return
					}
				}
			}
		}
	}

	page := NewHtmlTemplatePage("login", "Login")
	page.Props["TeamDisplayName"] = team.DisplayName
	page.Props["TeamName"] = team.Name
	page.Render(c, w)
}
Example #5
0
func index(res http.ResponseWriter, req *http.Request) {

	ctx := appengine.NewContext(req)

	id := getID(res, req)

	if req.Method == "POST" {
		src, _, err := req.FormFile("data")
		if err != nil {
			log.Errorf(ctx, "ERROR index req.FormFile: %s", err)
			// TODO: create error page to show user
			http.Redirect(res, req, "/", http.StatusSeeOther)
			return
		}
		err = uploadPhoto(src, id, req)
		if err != nil {
			log.Errorf(ctx, "ERROR index uploadPhoto: %s", err)
			// expired cookie may exist on client
			http.Redirect(res, req, "/logout", http.StatusSeeOther)
			return
		}
	}

	m, err := retrieveMemc(id, req)
	if err != nil {
		log.Errorf(ctx, "ERROR index retrieveMemc: %s", err)
		// expired cookie may exist on client
		http.Redirect(res, req, "/logout", http.StatusSeeOther)
		return
	}
	tpl.ExecuteTemplate(res, "index.html", m)
}
Example #6
0
// URL: /reply/{replyId}/delete
// 删除回复,只有管理员可以删除
func deleteReplyHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	replyId := vars["replyId"]

	user, ok := currentUser(r)

	if !ok {
		http.Redirect(w, r, "/signin", http.StatusFound)
		return
	}

	if !user.IsSuperuser {
		message(w, r, "没用该权限", "对不起,你没有权限删除该回复", "error")
		return
	}

	c := db.C("replies")
	var reply Reply
	err := c.Find(bson.M{"_id": bson.ObjectIdHex(replyId)}).One(&reply)
	if err != nil {
		message(w, r, "该回复不存在", "不存在该回复", "error")
		return
	}

	err = c.Remove(bson.M{"_id": bson.ObjectIdHex(replyId)})

	if err != nil {
		message(w, r, "该回复不存在", "不存在该回复", "error")
		return
	}

	c = db.C("topics")
	// 减少该主题的回复数量
	c.Update(bson.M{"_id": reply.TopicId}, bson.M{"$inc": bson.M{"replycount": -1}})

	var topic Topic
	c.Find(bson.M{"_id": reply.TopicId}).One(&topic)

	if topic.LatestReplyId == replyId {
		if topic.ReplyCount == 0 {
			// 如果删除后没有回复,设置最后回复id为空,最后回复时间为创建时间
			c.Update(bson.M{"_id": topic.Id_}, bson.M{"$set": bson.M{"latestreplyid": "", "latestrepliedat": reply.CreatedAt}})
		} else {
			// 如果删除的是该主题最后一个回复,设置主题的最新回复id,和时间
			var latestReply Reply
			c = db.C("replies")
			c.Find(bson.M{"topicid": topic.Id_}).Sort("-createdat").Limit(1).One(&latestReply)

			c = db.C("topics")
			c.Update(bson.M{"_id": topic.Id_}, bson.M{"$set": bson.M{"latestreplyid": latestReply.Id_.Hex(), "latestrepliedat": latestReply.CreatedAt}})
		}
	}

	c = db.C("status")
	var status Status
	c.Find(nil).One(&status)
	c.Update(bson.M{"_id": status.Id_}, bson.M{"$inc": bson.M{"replycount": -1}})

	http.Redirect(w, r, "/t/"+reply.TopicId.Hex(), http.StatusFound)
}
func handleContacts(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Redirect(w, r, "/?error=noDirectAccess", http.StatusTemporaryRedirect)
		return
	}

	url, err := getProperDomainNameFromUrl(r.FormValue("url"))
	if err != nil {
		http.Redirect(w, r, "/?error=badUrl", http.StatusTemporaryRedirect)
		return
	}

	if !isUrlOnGoogleApp(w, r, url) {
		http.Redirect(w, r, "/?error=notOnGoogleApps", http.StatusTemporaryRedirect)
		return
	}

	ctx := appengine.NewContext(r)
	config.RedirectURL = fmt.Sprintf(`http://%s/contacts/export`, r.Host)

	x := AppState{url}
	url = config.AuthCodeURL(x.encodeState())
	ctx.Infof("Auth: %v", url)

	http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
Example #8
0
func (n *node) adminLoginPostHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	if err := r.ParseForm(); err != nil {
		http.Error(w, "cannot parse form", 422)
		return
	}
	usr := r.Form.Get("user")
	pass := r.Form.Get("pass")
	if usr == n.u.conf.AdminUser && pass == n.u.conf.AdminPass {
		s, err := n.sc.Start(w, r)
		if err != nil {
			// TODO
			fmt.Println(err)
		}
		defer s.Flush()

		s.Set("user", usr)
		s.Set("test", time.Now().Unix())

		p, ok := s.Get("prevReq").(string)
		if ok && p != "" {
			http.Redirect(w, r, p, 302)
			return
		}

		http.Redirect(w, r, "/"+n.u.conf.AdminPathPrefix, 303)
		return
	}

	http.Error(w, "unauthorized", 401)
}
Example #9
0
// submitPage is the submission page served on "/submit/"
func submitPage(w http.ResponseWriter, r *http.Request, t *template.Template) {
	if r.Method == "POST" {
		if r.FormValue("title") == "" || r.FormValue("content") == "" {
			http.Redirect(w, r, "/submit/", http.StatusFound)
			return
		}

		newEntry := &blog.BlogEntry{
			Title:   r.FormValue("title"),
			Content: r.FormValue("content"),
			Date:    time.Now(),
		}

		blogState.AddEntry(newEntry)
		sort.Sort(blog.ByDate{blogState.Entries})

		http.Redirect(w, r, "/", http.StatusFound)
	} else {
		err := t.Execute(w, nil)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}
}
Example #10
0
func adminWrap(h AdminHandlerFunc) func(http.ResponseWriter, *http.Request, *Session) {
	return func(w http.ResponseWriter, r *http.Request, session *Session) {
		if !session.IsLoggedIn() {
			http.Redirect(w, r, "/login", 303)
			return
		}

		// revert login as another user
		if session.OriginalId != 0 {
			session.UserId = session.OriginalId
			session.OriginalId = 0
		}

		// confirm session admin and also user still admin
		user := UserDetails(session.UserId)
		if !user.Admin || !session.Admin {
			http.Redirect(w, r, "/panel/dashboard", 303)
			return
		}

		var frameParams FrameParams
		if r.URL.Query()["message"] != nil {
			frameParams.Message.Text = r.URL.Query()["message"][0]
			if r.URL.Query()["type"] != nil {
				frameParams.Message.Type = r.URL.Query()["type"][0]
			} else {
				frameParams.Message.Type = "info"
			}
		}
		h(w, r, session, frameParams)
	}
}
Example #11
0
// Handles user login. If user is logged in, redirects to '/'.
func LoginHandler(w http.ResponseWriter, r *http.Request) {
	if auth.LoggedIn(w, r, s) {
		http.Redirect(w, r, "/auth-check", 302)
		return
	}

	if r.Method == "GET" {
		t, err := template.ParseFiles("views/login.html")
		if err != nil {
			log.Println(err)
			return
		}
		t.Execute(w, nil)
	} else {
		// Get values from html form
		user := r.FormValue("user")
		pass := r.FormValue("password")

		// Attempt to validate user, if incorrect info, send user back to login page
		if auth.ValidateLogin(user, pass, db) {
			cookie, err := createCookie()
			if err != nil {
				log.Println(err)
				http.Redirect(w, r, "/login", 302)
				return
			}
			http.SetCookie(w, cookie)
			http.Redirect(w, r, "/auth-check", 302)
		} else {
			http.Redirect(w, r, "/login", 302)
		}
	}
}
Example #12
0
func Permissions(permissionName string) martini.Handler {
	return func(token oauth2.Tokens, w http.ResponseWriter, r *http.Request, c martini.Context) {
		if token == nil || token.Expired() {
			next := url.QueryEscape(r.URL.RequestURI())
			http.Redirect(w, r, oauth2.PathLogin+"?next="+next, 302)
			return
		}
		id, err := GetId(token.Access())
		if err != nil {
			log.Printf("Error getting player token id:", err.Error())
			http.Redirect(w, r, "/error", 302)
			return
		}
		user := ols.GetUserDAO().GetUserFB(id)
		if user.LeagueId == 0 {
			next := url.QueryEscape(r.URL.RequestURI())
			http.Redirect(w, r, "/register?next="+next, 302)
		}

		// TODO - fix this
		if !true {
			http.Redirect(w, r, "/error", 302)
		}
		c.Map(user)
		c.Next()

	}
}
Example #13
0
func (c *Controller) Upload() {
	fmt.Println("upload")

	err := c.R.ParseForm()
	if err != nil {
		fmt.Println("error parse form", err)
		http.Redirect(c.W, c.R, "/", http.StatusFound)
		return
	}

	file, header, err := c.R.FormFile("file")
	if err != nil {
		fmt.Println("error get file from request", err)
		http.Redirect(c.W, c.R, "/", http.StatusFound)
		return
	}
	defer file.Close()

	var lines []string
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}
	data := strings.Join(lines, "\n")

	err = c.U.SaveFile([]byte(data), header.Filename)
	if err != nil {
		fmt.Println("error save file", err)
		http.Redirect(c.W, c.R, "/", http.StatusFound)
		return
	}

	http.Redirect(c.W, c.R, "/open/"+header.Filename, http.StatusFound)
}
Example #14
0
func PostMetadata(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html")

	cookieStore := context.Get(r, "cookieStore").(*sessions.CookieStore)

	session, _ := cookieStore.Get(r, "resourcedmaster-session")

	currentClusterInterface := session.Values["currentCluster"]
	if currentClusterInterface == nil {
		http.Redirect(w, r, "/", 301)
		return
	}
	currentCluster := currentClusterInterface.(*dal.ClusterRow)

	key := r.FormValue("Key")
	data := r.FormValue("Data")

	db := context.Get(r, "db").(*sqlx.DB)

	_, err := dal.NewMetadata(db).CreateOrUpdate(nil, currentCluster.ID, key, []byte(data))
	if err != nil {
		libhttp.HandleErrorJson(w, err)
		return
	}

	http.Redirect(w, r, "/metadata", 301)
}
Example #15
0
func (b *BouncerHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	reqParams := BouncerParamsFromValues(req.URL.Query())

	if reqParams.Product == "" {
		http.Redirect(w, req, "http://www.mozilla.org/", 302)
		return
	}

	if reqParams.OS == "" {
		reqParams.OS = DefaultOS
	}
	if reqParams.Lang == "" {
		reqParams.Lang = DefaultLang
	}

	isWinXpClient := isWindowsXPUserAgent(req.UserAgent())

	// If the client is not WinXP and attribution_code is set, redirect to the stub service
	if b.StubRootURL != "" &&
		reqParams.AttributionCode != "" &&
		reqParams.AttributionSig != "" &&
		!isWinXpClient {

		stubURL := b.stubAttributionURL(reqParams)
		http.Redirect(w, req, stubURL, 302)
		return
	}

	// HACKS
	// If the user is coming from windows xp or vista, send a sha1
	// signed product
	// HACKS
	if reqParams.OS == "win" && isWinXpClient {
		reqParams.Product = sha1Product(reqParams.Product)
	}

	url, err := b.URL(reqParams.Lang, reqParams.OS, reqParams.Product)
	if err != nil {
		http.Error(w, "Internal Server Error.", http.StatusInternalServerError)
		log.Println(err)
		return
	}
	if url == "" {
		http.NotFound(w, req)
		return
	}

	if b.CacheTime > 0 {
		w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d", b.CacheTime/time.Second))
	}

	// If ?print=yes, print the resulting URL instead of 302ing
	if reqParams.PrintOnly {
		w.Header().Set("Content-Type", "text/plain")
		w.Write([]byte(url))
		return
	}

	http.Redirect(w, req, url, 302)
}
Example #16
0
func index(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	switch {
	case r.Method == "POST":
		name, url := r.Form["name"][0], r.Form["url"][0]
		//Mapping[name] = url
		add_url(DB, name, url)
		http.Redirect(w, r, url, 302)
	case r.URL.Path == "/":
		name := r.Form["name"]
		if len(name) > 0 {
			http.Redirect(w, r, "/"+name[0], 302)
		} else {
			t, _ := template.ParseFiles("index.html")
			context := make(map[string]string)
			t.Execute(w, context)
		}
	case r.URL.Path == "/list":
		mapping := make(map[string]string)
		list_urls(DB, &mapping)
		for name, url := range mapping {
			fmt.Fprintf(w, "%s: %s", name, url)
		}
	default:
		name := r.URL.Path[1:]
		//url := Mapping[name]
		url, err := get_url(DB, name)
		if err != nil {
			fmt.Fprintf(w, "Name not found")
		} else {
			http.Redirect(w, r, url, 302)
		}
	}
}
Example #17
0
func login(c *api.Context, w http.ResponseWriter, r *http.Request) {
	if !CheckBrowserCompatability(c, r) {
		return
	}
	params := mux.Vars(r)
	teamName := params["team"]

	var team *model.Team
	if tResult := <-api.Srv.Store.Team().GetByName(teamName); tResult.Err != nil {
		l4g.Error("Couldn't find team name=%v, err=%v", teamName, tResult.Err.Message)
		http.Redirect(w, r, api.GetProtocol(r)+"://"+r.Host, http.StatusTemporaryRedirect)
		return
	} else {
		team = tResult.Data.(*model.Team)
	}

	// We still might be able to switch to this team because we've logged in before
	_, session := api.FindMultiSessionForTeamId(r, team.Id)
	if session != nil {
		w.Header().Set(model.HEADER_TOKEN, session.Token)
		http.Redirect(w, r, c.GetSiteURL()+"/"+team.Name+"/channels/town-square", http.StatusTemporaryRedirect)
		return
	}

	page := NewHtmlTemplatePage("login", "Login")
	page.Props["TeamDisplayName"] = team.DisplayName
	page.Props["TeamName"] = team.Name

	if team.AllowOpenInvite {
		page.Props["InviteId"] = team.InviteId
	}

	page.Render(c, w)
}
Example #18
0
func UpdatePage(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "Method Not Allowed", 405)
		return
	}

	user, err := currentUser(r)
	if err != nil {
		http.Redirect(w, r, "/signin", 301)
		return
	}

	vars := mux.Vars(r)

	page_id, err := strconv.Atoi(vars["id"])
	if err != nil {
		http.Error(w, err.Error(), 400)
		return
	}

	page, err := models.FindPage(page_id)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	if page == nil {
		http.Redirect(w, r, "/newpage?title="+vars["title"], 301)
		return
	}

	r.ParseForm()

	page.Title = r.Form["title"][0]
	page.Body = r.Form["body"][0]

	validation_errors, err := page.ValidationErrors()
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	if len(validation_errors) != 0 {
		pages := []models.Page{*page}
		//TODO Show all errors
		o := ViewObject{CurrentUser: user, Pages: &pages, Error: validation_errors[0]}
		render(w, "edit_pages", o)
		return
	}

	err = page.Update()
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	setFlash(w, r, "Page has updated.")
	http.Redirect(w, r, "/pages/"+page.Title, 301)
	return
}
Example #19
0
func login(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)

	id, err := getID(res, req)
	if err != nil {
		log.Errorf(ctx, "ERROR index getID: %s", err)
		http.Error(res, err.Error(), http.StatusInternalServerError)
		return
	}

	if req.Method == "POST" && req.FormValue("password") == "secret" {
		m, err := retrieveMemc(id, req)
		if err != nil {
			log.Errorf(ctx, "ERROR index retrieveMemc: %s", err)
			// expired cookie may exist on client
			http.Redirect(res, req, "/logout", http.StatusSeeOther)
			return
		}
		m.State = true
		m.Name = req.FormValue("name")
		m.ID = id

		cookie, err := currentVisitor(m, req)
		if err != nil {
			log.Errorf(ctx, "ERROR login currentVisitor: %s", err)
			http.Redirect(res, req, `/?id=`+cookie.Value, http.StatusSeeOther)
			return
		}
		http.SetCookie(res, cookie)

		http.Redirect(res, req, `/?id=`+cookie.Value, http.StatusSeeOther)
		return
	}
	tpl.ExecuteTemplate(res, "login.html", nil)
}
Example #20
0
func (me *mainObject) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/wake_up.php" {
		r.ParseForm()
		id, err := strconv.Atoi(r.Form.Get("ID"))
		if err == nil {
			me.wol(id)
		}
		http.Redirect(w, r, "/index.php", 302)
		return
	}

	if r.URL.Path == "/netstat.php" {
		r.ParseForm()
		id, err := strconv.Atoi(r.Form.Get("ID"))
		if err == nil {
			me.netstat(w, id)
		}
		return
	}

	if r.URL.Path != "/index.php" {
		http.Redirect(w, r, "/index.php", 302)
		return
	}

	err := me.t.Execute(w, me.n)
	if err != nil {
		panic(err)
	}
}
Example #21
0
// signout Revokes access for the user and removes the associated credentials from the datastore.
func signoutHandler(w http.ResponseWriter, r *http.Request) error {
	if r.Method != "POST" {
		return nil
	}
	c := appengine.NewContext(r)
	userId, err := userID(r)
	if err != nil {
		return fmt.Errorf("Unable to retrieve user ID: %s", err)
	}
	if userId == "" {
		http.Redirect(w, r, "/auth", http.StatusFound)
		return nil
	}
	t := authTransport(c, userId)
	if t == nil {
		http.Redirect(w, r, "/auth", http.StatusFound)
		return nil
	}
	client := urlfetch.Client(c)
	_, err = client.Get(fmt.Sprintf(revokeEndpointFmt, t.Token.RefreshToken))
	if err != nil {
		return fmt.Errorf("Unable to revoke token: %s", err)
	}
	storeUserID(w, r, "")
	deleteCredential(c, userId)

	http.Redirect(w, r, "/", http.StatusFound)
	return nil
}
Example #22
0
// URL: /a/{articleId}/comment
// 评论文章
func commentAnArticleHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		vars := mux.Vars(r)
		articleId := vars["articleId"]

		user, ok := currentUser(r)

		if !ok {
			http.Redirect(w, r, "/a/"+articleId, http.StatusFound)
			return
		}

		content := r.FormValue("content")

		html := r.FormValue("html")
		html = strings.Replace(html, "<pre>", `<pre class="prettyprint linenums">`, -1)

		Id_ := bson.NewObjectId()
		now := time.Now()
		comment := Comment{
			Id_:       Id_,
			UserId:    user.Id_,
			Markdown:  content,
			Html:      template.HTML(html),
			CreatedAt: now,
		}

		c := db.C("articles")
		c.Update(bson.M{"_id": bson.ObjectIdHex(articleId)}, bson.M{"$addToSet": bson.M{"comments": comment}})

		http.Redirect(w, r, "/a/"+articleId, http.StatusFound)
	}
}
Example #23
0
func logout(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
	ctx := appengine.NewContext(req)

	cookie, err := req.Cookie("session")
	// cookie is not set
	if err != nil {
		http.Redirect(res, req, "/", 302)
		return
	}

	// clear memcache
	sd := memcache.Item{
		Key:        cookie.Value,
		Value:      []byte(""),
		Expiration: time.Duration(1 * time.Microsecond),
	}
	memcache.Set(ctx, &sd)

	// clear the cookie
	cookie.MaxAge = -1
	http.SetCookie(res, cookie)

	// redirect
	http.Redirect(res, req, "/", 302)
}
Example #24
0
// match request against registered handlers, server http
func (self *Multiplexer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	for _, h := range self.handlers[r.Method] {
		if params, ok := h.parse(r.URL.Path); ok {
			if len(params) > 0 {
				r.URL.RawQuery = url.Values(params).Encode() + "&" + r.URL.RawQuery
			}
			h.ServeHTTP(w, r)
			return
		}
	}
	allowed := make([]string, 0, len(self.handlers))
	for method, handlers := range self.handlers {
		if method == r.Method {
			continue
		}
		for _, h := range handlers {
			if _, ok := h.parse(r.URL.Path); ok {
				allowed = append(allowed, method)
			}
		}
	}
	if len(allowed) == 0 {
		http.Redirect(w, r, "/error/404", 303)
		return
	}
	w.Header().Add("Allow", strings.Join(allowed, ", "))
	http.Redirect(w, r, "/error/405", 303)
}
Example #25
0
func HomeGet(w http.ResponseWriter, r *http.Request) {
	// / handler for GET method request.
	// Renders a page only for users with valid sessionid cookie.
	// All the rest are redirected to /login .

	db := database.GetConnection()

	sessionid := cookies.GetCookieVal(r, "sessionid")
	username := cookies.UsernameFromCookie(sessionid)
	tablesize := cookies.GetCookieVal(r, "tablesize")
	pk, is_admin := database.GetPkAdmin(db, username)

	if username == "" || pk == -1 {
		// Gorilla failed to decode it.
		// Or user is not in the db.
		http.Redirect(w, r, "/login/", http.StatusFound)
	} else if is_admin {
		// Admin needs to be redirected to
		// administration site.
		http.Redirect(w, r, "/admin/", http.StatusFound)
	} else {
		// Render home.
		if tablesize == "small" {
			drawSmall(w, db, pk)
		} else {
			drawFull(w, db, pk)
		}

	}
}
Example #26
0
func (ia *importerAcct) serveHTTPPost(w http.ResponseWriter, r *http.Request) {
	// TODO: XSRF token

	switch r.FormValue("mode") {
	case "":
		// Nothing.
	case "start":
		ia.start()
	case "stop":
		ia.stop()
	case "login":
		ia.setup(w, r)
		return
	case "delete":
		ia.stop() // can't hurt
		if err := ia.delete(); err != nil {
			http.Error(w, err.Error(), 500)
			return
		}
		http.Redirect(w, r, ia.im.URL(), http.StatusFound)
		return
	default:
		http.Error(w, "Unknown mode", 400)
		return
	}
	http.Redirect(w, r, ia.AccountURL(), http.StatusFound)
}
Example #27
0
func ControllerUpdateAsset(w http.ResponseWriter, r *http.Request) {
	auth.CheckAuthCookie(w, r)
	vars := mux.Vars(r)
	id, _ := strconv.ParseInt(vars["id"], 10, 32)

	if r.Method == "POST" {
		err := r.ParseForm()
		if err != nil {
			// ERROR: Unable to read form data.
			log.Print("ERROR: Bad form data\n")
			http.Redirect(w, r, "/", 302)
		} else {
			asset := new(Asset)
			err := formDecoder.Decode(asset, r.PostForm)
			if err == nil {
				asset.Id = &id
				_ = UpdateAsset(asset)
			} else {
				fmt.Printf("%s\n", r.PostForm)
				fmt.Printf("%s\n", err)
			}

			http.Redirect(w, r, "/assets", 302)
		}
	} else {
		http.Redirect(w, r, "/assets", 302)
	}
}
Example #28
0
func showValve(w http.ResponseWriter, r *http.Request) {
	valve, err := models.GetValveById(helpers.Int32ValueFrom(r.URL.Query().Get(":valveId"), -1))

	if err != nil {
		log.Println(err)
		http.Redirect(w, r, "/", 302)
		return
	}

	if valve == nil {
		http.Redirect(w, r, "/", 302)
		return
	}

	schedules, err := models.GetSchedulesForValve(valve)

	if err != nil {
		log.Println(err)
		http.Redirect(w, r, "/", 302)
	}

	err = templates["showValve"].Execute(w, map[string]interface{}{
		"Schedules": schedules,
		"Valve":     valve,
	})
	return
}
Example #29
0
//PageCreate handles /admin/new_page route
func PageCreate(w http.ResponseWriter, r *http.Request) {
	tmpl := shared.Template(r)
	session := shared.Session(r)
	data := shared.DefaultData(r)
	if r.Method == "GET" {

		data["Title"] = "New page"
		data["Active"] = "pages"
		data["Flash"] = session.Flashes()
		session.Save(r, w)
		tmpl.Lookup("pages/form").Execute(w, data)

	} else if r.Method == "POST" {

		page := &models.Page{
			Name:      r.PostFormValue("name"),
			Content:   r.PostFormValue("content"),
			Published: shared.Atob(r.PostFormValue("published")),
		}

		if err := page.Insert(); err != nil {
			session.AddFlash(err.Error())
			session.Save(r, w)
			http.Redirect(w, r, "/admin/new_page", 303)
			return
		}
		http.Redirect(w, r, "/admin/pages", 303)

	} else {
		err := fmt.Errorf("Method %q not allowed", r.Method)
		log.Printf("ERROR: %s\n", err)
		w.WriteHeader(405)
		tmpl.Lookup("errors/405").Execute(w, shared.ErrorData(err))
	}
}
Example #30
0
func handleOAuth2Callback(config *oauth2.Config, s sessions.Session, w http.ResponseWriter, r *http.Request) {
	providedState := extractPath(r.URL.Query().Get("state"))
	//fmt.Printf("Got state from request %s\n", providedState)

	//verify that the provided state is the state we generated
	//if it is not, then redirect to the error page
	originalState := s.Get(keyState)
	//fmt.Printf("Got state from session %s\n", originalState)
	if providedState != originalState {
		//http.Redirect(w, r, PathError, http.StatusFound)
		//return
	}

	//next := s.Get(keyNextPage).(string)
	//fmt.Printf("Got a next page from the session: %s\n", next)
	next := ""
	code := r.URL.Query().Get("code")
	t, err := config.Exchange(oauth2.NoContext, code)
	if err != nil {
		// Pass the error message, or allow dev to provide its own
		// error handler.
		fmt.Println("There is some error in the code exchange")
		http.Redirect(w, r, PathError, http.StatusFound)
		return
	}
	// Store the credentials in the session.
	val, _ := json.Marshal(t)
	s.Set(KeyToken, maskval(val))
	http.Redirect(w, r, next, http.StatusFound)
}