diff options
| author | Horus_Arch | 2015-03-02 15:31:39 +0100 |
|---|---|---|
| committer | Horus_Arch | 2015-03-02 15:31:39 +0100 |
| commit | e31b06b7b56aaf1cf5510d4bb0261f73bc0e8893 (patch) | |
| tree | 0651cdd688659b845f3605e09384161b3c0334db /app/controllers | |
| parent | cf66deeeba38263feef0ca4123a983cb78ce5cac (diff) | |
| download | webmon-e31b06b7b56aaf1cf5510d4bb0261f73bc0e8893.tar.gz | |
Diffstat (limited to 'app/controllers')
| -rw-r--r-- | app/controllers/app.go | 195 | ||||
| -rw-r--r-- | app/controllers/db.go | 119 | ||||
| -rw-r--r-- | app/controllers/mail.go | 45 | ||||
| -rw-r--r-- | app/controllers/utilities.go | 94 |
4 files changed, 0 insertions, 453 deletions
diff --git a/app/controllers/app.go b/app/controllers/app.go deleted file mode 100644 index 9e5764f..0000000 --- a/app/controllers/app.go +++ /dev/null @@ -1,195 +0,0 @@ -package controllers - -import ( - "github.com/jinzhu/gorm" - "github.com/revel/revel" - "github.com/revel/revel/modules/jobs/app/jobs" -) - -type App struct { - *revel.Controller -} - -func (c App) Index() revel.Result { - return c.Render() -} - -func (c App) PrintLogin(legacy bool) revel.Result { - return c.Render(legacy) -} - -func (c App) PrintRegister() revel.Result { - return c.Render() -} - -func (c App) Account() revel.Result { - return c.Render() -} - -func (c App) Login(email string, legacy bool, user string, password string, passwordConfirm string) revel.Result { - - if legacy { - // Show login form with username and password - c.Validation.Required(user).Message("Please enter a user name.") - c.Validation.Required(password).Message("Please enter a password.") - c.Validation.Required(passwordConfirm).Message("Please confirm your password.") - c.Validation.Required(password == passwordConfirm).Message("The passwords do not match.") - } else { - // Show login form only with email - c.Validation.Required(email).Message("Please provide a mail adress.") - } - - if c.Validation.HasErrors() { - c.Validation.Keep() - c.FlashParams() - return c.Redirect(App.PrintLogin) - } - - u := User{} - if legacy { - // do database lookup and show if its matched - db.Where("name = ?", user).First(&u) - c.Validation.Required(u.Confirmed).Message("Your mail adress is not confirmed yet.") - verify, _ := VerifyPassword(password, u.Password) - c.Validation.Required(verify).Message("The user/password combination does not exists.") - - if c.Validation.HasErrors() { - c.Validation.Keep() - c.FlashParams() - return c.Redirect(App.PrintLogin) - } - - c.Session["login"] = "true" - c.Session["uid"] = string(u.Id) - - return c.Redirect(App.Account) - } else { - if db.Where("email = ?", email).First(&u).Error == gorm.RecordNotFound { - // Invalid Email - c.Flash.Error("No valid mail adress.") - return c.Redirect(App.PrintLogin) - } - // Get random string - key := RandomKey() - // Set key in redis - conn := pool.Get() - defer conn.Close() - _, _ = conn.Do("SET", key, u.Email, 86400) - // Send email with confirmation link - //jobs.Now(Mailer{}.SendConfirmationKey(email, key)) - _ = Mailer{}.SendConfirmationKey(email, key) - - c.Flash.Success("A mail with a confirmation link was sent. Follow the instructions there.") - - return c.Redirect(App.PrintLogin) - } -} - -func (c App) Confirm(key, registration string) revel.Result { - - if registration == "" { - // Processing login - - c.Validation.Required(key).Message("No key provided.") - - conn := pool.Get() - confirmKey, err := conn.Do("GET", key) - c.Validation.Required(err == nil).Message("Oops, there is currently an internal problem. Please check later again.") - c.Validation.Required(confirmKey).Message("Key does not seem to be valid.") - - _, _ = conn.Do("DEL", key) - - if c.Validation.HasErrors() { - c.Validation.Keep() - c.FlashParams() - return c.Redirect(App.PrintLogin) - } - - u := User{} - db.Where("email = ?", confirmKey).First(&u) - - if u.Confirmed == false { - // E-Mail is now confirmed - u.Confirmed = true - u.ConfirmationKey = "" - db.Save(&u) - } - - c.Session["login"] = "true" - c.Session["uid"] = string(u.Id) - - } else { - // Processing registration confirmation - - c.Validation.Required(registration).Message("No confirmation key provided.") - - u := User{} - db.Where("confirmationkey = ?").First(&u) - - c.Validation.Required(registration == u.ConfirmationKey).Message("Key does not seem to be valid.") - - if c.Validation.HasErrors() { - c.Validation.Keep() - c.FlashParams() - return c.Redirect(App.PrintLogin) - } - - u.Confirmed = true - u.ConfirmationKey = "" - db.Save(&u) - - c.Session["login"] = "true" - c.Session["uid"] = string(u.Id) - - } - - return c.Redirect(App.Account) -} - -func (c App) Register(email, confirmEmail, user, password, confirmPassword string) revel.Result { - - c.Validation.Required(email).Message("Please provide a mail adress.") - c.Validation.Required(email == confirmEmail).Message("The mail adresses do not match.") - c.Validation.Required(user).Message("Please provide a user name.") - - if password != "" { - c.Validation.Required(password == confirmPassword).Message("Passwords do not match.") - } - - if c.Validation.HasErrors() { - c.Validation.Keep() - c.FlashParams() - return c.Redirect(App.PrintRegister) - } - - p, _ := HashPassword(password) - key := RandomKey() // Create key to confirm mail adress - u := User{ - Name: user, - Email: email, - Password: p, - Confirmed: false, - ConfirmationKey: key, - Alerts: []Alert{{Email: email}}, - } - - db.NewRecord(u) - db.Create(&u) - db.Save(&u) - - // Send email with confirmation link - //jobs.Now(Mailer{}.ConfirmRegistration(email, key)) - //_ = Mailer{}.ConfirmRegistration(user, email, key) - jobs.Now(JobRegistration{User: user, Email: email, Key: key}) - c.Flash.Success("A mail with a confirmation link was sent. Please confirm your mail adress now.") - - return c.Redirect(App.PrintRegister) -} - -func (c App) Test(email, key string) revel.Result { - // jobs.Now(JobRegistration{User: "foobar", Email: email, Key: key}) - Mailer{}.ConfirmRegistration("foobar", "raspi@dns.iamfabulous.de", "string") - c.Flash.Success("A mail with a confirmation link was sent. Please confirm your mail adress now.") - - return c.Redirect(App.Index) -} diff --git a/app/controllers/db.go b/app/controllers/db.go deleted file mode 100644 index baa772c..0000000 --- a/app/controllers/db.go +++ /dev/null @@ -1,119 +0,0 @@ -package controllers - -import ( - "github.com/jinzhu/gorm" - _ "github.com/mattn/go-sqlite3" - "github.com/revel/revel" - "time" -) - -type User struct { - Id int64 - Email string `sql:"unique"` - Name string `sql:"unique"` - Password string - Confirmed bool - ConfirmationKey string - Alerts []Alert - CreatedAt time.Time - DeletedAt time.Time - UpdatedAt time.Time -} - -// Multiple accounts which are alerted -type Alert struct { - Id int64 - UserId int64 - Email string - CreatedAt time.Time - DeletedAt time.Time - UpdatedAt time.Time -} - -type Job struct { - Id int64 - UserId int64 - Name string - Url string - Versions []Version - Diff string - DiffLen int64 - CreatedAt time.Time - DeletedAt time.Time - UpdatedAt time.Time -} - -// Save history version of jobs -type Version struct { - Id int64 - JobId int64 - Content string - Hash string - CreatedAt time.Time - DeletedAt time.Time - UpdatedAt time.Time -} - -var db = DBInit() - -func DBInit() gorm.DB { - // Open database handler - // !!! FIXME THIS THROWS A PANIC AT COMPILE TIME. WHY? !!! - - //db, err := gorm.Open(revel.Config.StringDefault("db.driver", "sqlite3"), revel.Config.StringDefault("db.spec", "webmon.db")) - - /* OR */ - - /* - var ( - d, s string - ) - d = revel.Config.StringDefault("test.d", "sqlite3") - s = revel.Config.StringDefault("test.s", "webmon.db") - //db, err := gorm.Open(driver, spec) - - revel.WARN.Println(d) - revel.WARN.Println(s) - */ - - // This works. - db, err := gorm.Open("sqlite3", "webmon.db") - - // Set database logging to TRACE - db.LogMode(true) - db.SetLogger(gorm.Logger{revel.TRACE}) - - // Ping database to check if up - if err = db.DB().Ping(); err != nil { - revel.ERROR.Panicf("Failed to init database. %s \n", err) - } - defer db.Close() - - // Set Pool connections - db.DB().SetMaxIdleConns(10) - db.DB().SetMaxOpenConns(100) - - // Create tables which are defined as struct - db.Debug().CreateTable(&User{}) - db.Debug().CreateTable(&Alert{}) - db.Debug().CreateTable(&Job{}) - db.Debug().CreateTable(&Version{}) - - // Automigration - db.Debug().AutoMigrate(&User{}, &Job{}, &Version{}, &Alert{}) - - // Add index on email and name to enforce uniqueness - db.Debug().Model(&User{}).AddUniqueIndex("idx_user_email", "email") - db.Debug().Model(&User{}).AddUniqueIndex("idx_user_name", "name") - - // Unique index on alert to ensure every user can specify not multiple equally alerts - db.Debug().Model(&Alert{}).AddUniqueIndex("idx_alert_email_userid", "email", "user_id") - - // Unique index to ensure every user can have only one job with the same name - db.Debug().Model(&Job{}).AddUniqueIndex("idx_job_name_userid", "name", "user_id") - - // Makes hash unique - // db.Debug().Model(&Version{}).AddUniqueIndex("idx_version_hash", "hash") - - return db -} diff --git a/app/controllers/mail.go b/app/controllers/mail.go deleted file mode 100644 index 3fd2e94..0000000 --- a/app/controllers/mail.go +++ /dev/null @@ -1,45 +0,0 @@ -package controllers - -import ( - "github.com/tanema/revel_mailer" -) - -type Mailer struct { - revel_mailer.Mailer -} - -type JobConfirmationKey struct { - Email string - Key string -} - -func (j JobConfirmationKey) Run() { - _ = Mailer{}.SendConfirmationKey(j.Email, j.Key) -} - -func (u Mailer) SendConfirmationKey(email, key string) error { - return u.Send(revel_mailer.H{ - "subject": "Confirmation Key", - "to": []string{email}, - "key": key, - }) -} - -type JobRegistration struct { - User string - Email string - Key string -} - -func (j JobRegistration) Run() { - _ = Mailer{}.ConfirmRegistration(j.User, j.Email, j.Key) -} - -func (u Mailer) ConfirmRegistration(user, email, key string) error { - return u.Send(revel_mailer.H{ - "name": user, - "subject": "Confirm registration", - "to": []string{email}, - "key": key, - }) -} diff --git a/app/controllers/utilities.go b/app/controllers/utilities.go deleted file mode 100644 index 1aa5d6d..0000000 --- a/app/controllers/utilities.go +++ /dev/null @@ -1,94 +0,0 @@ -package controllers - -import ( - "crypto/md5" - "fmt" - "github.com/garyburd/redigo/redis" - "github.com/revel/revel" - "golang.org/x/crypto/bcrypt" - "io" - "io/ioutil" - "math/rand" - "net/http" - "time" -) - -// Returns the content of a webpage as string -func Get(url string) (string, error) { - response, err := http.Get(url) - if err != nil { - return "Get request failed.", err - } - - defer response.Body.Close() - contents, err := ioutil.ReadAll(response.Body) - if err != nil { - return "Reading body failed.", err - } - - return string(contents), nil -} - -// Hashs and returns a string (md5) -func Hash(content string) string { - h := md5.New() - io.WriteString(h, content) - hash := fmt.Sprintf("%x", h.Sum(nil)) - - return hash -} - -// Creates a random string -func RandomKey() string { - letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") - key := make([]rune, 40) - for i := range key { - key[i] = letters[rand.Intn(len(letters))] - } - - return string(key) -} - -var pool = newPool() - -// Creates a pool with connections to Redis -func newPool() *redis.Pool { - return &redis.Pool{ - MaxIdle: 3, - IdleTimeout: 240 * time.Second, - Dial: func() (redis.Conn, error) { - //c, err := redis.Dial("tcp", ":6379") - c, err := redis.Dial("tcp", revel.Config.StringDefault("redis.server", "127.0.0.1")+":"+revel.Config.StringDefault("redis.port", "6379")) - if err != nil { - return nil, err - } - return c, err - }, - TestOnBorrow: func(c redis.Conn, t time.Time) error { - _, err := c.Do("PING") - return err - }, - } -} - -// Hashs password with bcrypt and returns the string -func HashPassword(password string) (string, error) { - if password == "" { - return "", nil - } - p := []byte(password) - hash, err := bcrypt.GenerateFromPassword(p, 10) - if err != nil { - return "", err - } - return string(hash), nil -} - -// Verify password and hash -func VerifyPassword(password, hash string) (bool, error) { - err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) - if err != nil { - return false, err - } - return true, nil -} |
