Example #1
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))
}
Example #2
0
func main() {
	store := sessions.NewCookieStore([]byte("secret123"))
	dbmap = initDb()

	m := martini.Classic()
	m.Use(render.Renderer())

	// Default our store to use Session cookies, so we don't leave logged in
	// users roaming around
	store.Options(sessions.Options{
		MaxAge: 0,
	})
	m.Use(sessions.Sessions("my_session", store))
	m.Use(sessionauth.SessionUser(GenerateAnonymousUser))
	sessionauth.RedirectUrl = "/login"
	sessionauth.RedirectParam = "index"

	m.Get("/", func(r render.Render) {
		r.HTML(200, "index", nil)
	})

	m.Get("/login", func(r render.Render) {
		r.HTML(200, "login", nil)
	})

	m.Post("/new-login", binding.Bind(MyUserModel{}), func(session sessions.Session, postedUser MyUserModel, r render.Render, req *http.Request) {
		// You should verify credentials against a database or some other mechanism at this point.
		// Then you can authenticate this session.
		user := MyUserModel{}
		err := dbmap.SelectOne(&user, "SELECT * FROM users WHERE username = $1 and password = $2", postedUser.Username, postedUser.Password)
		if err != nil {
			r.Redirect(sessionauth.RedirectUrl)
			return
		} else {
			err := sessionauth.AuthenticateSession(session, &user)
			if err != nil {
				r.JSON(500, err)
			}

			params := req.URL.Query()
			redirect := params.Get(sessionauth.RedirectParam)
			r.Redirect(redirect)
			return
		}
	})

	m.Get("/private", sessionauth.LoginRequired, func(r render.Render, user sessionauth.User) {
		r.HTML(200, "private", user.(*MyUserModel))
	})

	m.Get("/logout", sessionauth.LoginRequired, func(session sessions.Session, user sessionauth.User, r render.Render) {
		sessionauth.Logout(session, user)
		r.Redirect("/")
	})

	m.Run()
}
Example #3
0
func main() {
	m := martini.Classic()

	m.Use(render.Renderer(render.Options{
		Layout: "_layout",
	}))

	m.Use(secure.Secure(secure.Options{
		SSLRedirect:     true,
		SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"},
	}))
	store := sessions.NewCookieStore([]byte(os.Getenv("COOKIE_SECRET")))
	m.Use(sessions.Sessions("the_session", store))
	m.Use(sessionauth.SessionUser(GenerateAnonymousUser))

	/** Main router **/

	m.Get("/", sessionauth.LoginRequired, cameraList)
	m.Get("/camimage", sessionauth.LoginRequired, cameraImage)

	/** Login Handling **/

	m.Get("/login", func(r render.Render) {
		r.HTML(200, "login", nil, render.HTMLOptions{
			Layout: "_login_layout",
		})
	})

	m.Post("/login", binding.Bind(User{}), func(session sessions.Session, postedUser User, r render.Render, req *http.Request) {

		// if not logged in
		if postedUser.Passcode != "" && postedUser.Passcode == os.Getenv("WEB_PASSCODE") {
			user := &User{}
			err := sessionauth.AuthenticateSession(session, user)
			if err != nil {
				r.Text(500, "Error authenticating session")
				return
			}

			params := req.URL.Query()
			redirect := params.Get(sessionauth.RedirectParam)
			r.Redirect(redirect)
			return
		} else {
			r.Redirect(sessionauth.RedirectUrl)
			return

		}
	})

	m.Get("/logout", sessionauth.LoginRequired, func(session sessions.Session, user sessionauth.User, r render.Render) {
		sessionauth.Logout(session, user)
		r.Redirect("/")
	})

	m.Run()
}
Example #4
0
func (u UserHandler) Login(session sessions.Session, postedUser model.UserModel, db *mgo.Database, r render.Render) {
	// load user  from database
	user := model.UserModel{}
	err := db.C("users").Find(bson.M{"username": postedUser.Username}).One(&user)
	if err != nil {
		r.Redirect(sessionauth.RedirectUrl)
		return
	}
	fmt.Printf("Login postedUser:%v \n", postedUser)

	//verify credentials
	HashOfPostedPw, err := scrypt.Key([]byte(postedUser.Password), user.Salt, 16384, 8, 1, 32)
	//fmt.Printf("Login user.HashedPassword:\n%v\n", user.HashedPassword)
	//fmt.Printf("Login HashOfPostedPw:\n%v\n", HashOfPostedPw)
	if err != nil || bytes.Compare(user.HashedPassword, HashOfPostedPw) != 0 {
		fmt.Println("Login - Login Failed")
		r.Redirect(sessionauth.RedirectUrl)
		return
	}

	// authenticate the session
	err = sessionauth.AuthenticateSession(session, &user)
	if err != nil {
		r.Redirect("/signin")
		return
	}
	fmt.Printf("Login Success, AUTHUNIQUEID:%v \n", session.Get("AUTHUNIQUEID"))

	// TODO: Why is req.URL empty?...
	// fmt.Println("ValidateLogin - RawQuery:", req.URL.RawQuery)
	// params := req.URL.Query().Get(sessionauth.RedirectParam)
	// fmt.Println("ValidateLogin - Params:", params)
	// redirect := params.Get(sessionauth.RedirectParam)
	// fmt.Println("Redirecting:", redirect)
	//r.Redirect("/dashboard")
	//session.Set("id", user.Id)

	r.HTML(200, "dashboard", user)
	return
}
Example #5
0
func GetConfirmAccount(session sessions.Session, rw http.ResponseWriter, req *http.Request, params martini.Params) {
	account, err := FindAccountByConfirmationToken(params["confirmation_token"])
	if err != nil {
		panic(err)
	}

	_, err = dbmap.Exec(
		"update accounts set confirmed_at = $1 where id = $2",
		time.Now(),
		account.Id,
	)
	if err != nil {
		panic(err)
	}

	err = sessionauth.AuthenticateSession(session, account)
	if err != nil {
		panic(err)
	}

	http.Redirect(rw, req, "/account", http.StatusFound)
}
Example #6
0
func postLoginHandler(session sessions.Session, userLoggingIn User, r render.Render, req *http.Request) {
	if session.Get(sessionauth.SessionKey) != nil {
		fmt.Println("Logged in already! Logout first.")
		r.Redirect(INDEX_PAGE)
		return
	}

	var userInDb User
	query := rethink.Table("user").Filter(rethink.Row.Field("email").Eq(userLoggingIn.Email))
	row, err := query.RunRow(dbSession)

	// TODO do flash errors
	if err == nil && !row.IsNil() {
		if err := row.Scan(&userInDb); err != nil {
			r.Redirect(sessionauth.RedirectUrl)
			return
		}
	} else {
		fmt.Println(err)
		r.Redirect(sessionauth.RedirectUrl)
		return
	}

	passErr := bcrypt.CompareHashAndPassword([]byte(userInDb.Password), []byte(userLoggingIn.Password))
	if passErr != nil {
		fmt.Println("Wrong Password")
		r.Redirect(sessionauth.RedirectUrl)
	} else {
		err := sessionauth.AuthenticateSession(session, &userInDb)
		if err != nil {
			fmt.Println("Wrong Auth")
			r.JSON(500, err)
		}
		params := req.URL.Query()
		redirect := params.Get(sessionauth.RedirectParam)
		r.Redirect(redirect)
	}
}
Example #7
0
func (web *MailWeb) authenticate(session sessions.Session, postedUser auth.WatneyUser,
	r render.Render, req *http.Request) {
	// 1) Create a new IMAP mail server connection
	if imapCon, err := mail.NewMailCon(web.mconf); nil != err {
		fmt.Printf("Couldn't establish connection to imap mail server: %s\n", err.Error())
		r.HTML(200, "start", map[string]interface{}{
			"FailedLogin": true,
			"OrigError":   err.Error(),
		})
	} else {
		if _, err := imapCon.Authenticate(postedUser.Username, postedUser.Password); err == nil {
			var user auth.WatneyUser = auth.WatneyUser{
				Username: postedUser.Username,
				SMTPAuth: smtp.PlainAuth("", postedUser.Username, postedUser.Password,
					web.mconf.SMTPAddress),
				ImapCon: imapCon,
			}
			h := fnv.New32a()
			h.Write([]byte(postedUser.Username))
			user.Id = int64(h.Sum32())
			if err := sessionauth.AuthenticateSession(session, &user); err != nil {
				r.HTML(200, "start", map[string]interface{}{
					"FailedLogin": true,
					"OrigError":   err.Error(),
				})
			}
			r.Redirect("/main")
		} else {
			fmt.Println("FAILED!")
			imapCon.Close()
			r.HTML(200, "start", map[string]interface{}{
				"FailedLogin": true,
				"OrigError":   err.Error(),
			})
		}
	}
}
Example #8
0
func (self *oprloginComponent) Start(peer netfw.IPeer) {

	m := peer.(martinihttp.IMartiniAcceptor).GetInterface()

	var config coredef.OperateConfig
	netfw.GetConfig("OperateConfig", &config)

	store := sessions.NewCookieStore([]byte("secret123"))

	store.Options(sessions.Options{
		MaxAge: 0,
	})

	m.Use(sessions.Sessions("my_session", store))
	m.Use(sessionauth.SessionUser(GenerateAnonymousUser))

	// 显示登陆页面
	m.Get("/login", func(r render.Render) {
		r.HTML(200, "login", nil)
	})

	// 提交登陆
	m.Post("/login", binding.Bind(gmUserPostForm{}), func(session sessions.Session, msg gmUserPostForm, r render.Render, req *http.Request) {

		var verify bool

		for _, v := range config.GetAccount() {
			if msg.UserName == v.GetAccount() && msg.Password == EncodePassword(v.GetPassword()) {
				verify = true
				break
			}
		}

		if !verify {
			r.Redirect("login")
		}

		err := sessionauth.AuthenticateSession(session, &User{AutoID: 1})
		if err != nil {
			r.JSON(500, err)
		}

		r.Redirect("index")

	})

	// 登出
	m.Get("/logout", sessionauth.LoginRequired, func(session sessions.Session, user sessionauth.User, r render.Render) {
		sessionauth.Logout(session, user)
		r.Redirect("/login")
	})

	m.Get("/index", sessionauth.LoginRequired, func(r render.Render) {
		r.HTML(200, "index", nil)
	})

	m.Get("/", func(r render.Render) {
		r.Redirect("index")
	})

}