1
0
Fork 0
forked from forgejo/forgejo

basic authentications

This commit is contained in:
Lunny Xiao 2014-05-05 16:40:25 +08:00
parent 79ea34e70e
commit 1652dd5068
13 changed files with 334 additions and 49 deletions

View file

@ -2,17 +2,31 @@ package models
import (
"encoding/json"
"errors"
"time"
"github.com/go-xorm/core"
"github.com/go-xorm/xorm"
"github.com/gogits/gogs/modules/auth/ldap"
)
/*const (
// Login types.
const (
LT_PLAIN = iota + 1
LT_LDAP
LT_SMTP
)*/
)
var (
ErrAuthenticationAlreadyExist = errors.New("Authentication already exist")
ErrAuthenticationNotExist = errors.New("Authentication is not exist")
ErrAuthenticationUserUsed = errors.New("Authentication has been used by some users")
)
var LoginTypes = map[int]string{
LT_LDAP: "LDAP",
LT_SMTP: "SMTP",
}
var _ core.Conversion = &LDAPConfig{}
@ -32,19 +46,50 @@ func (cfg *LDAPConfig) ToDB() ([]byte, error) {
type LoginSource struct {
Id int64
Type int
Name string
IsActived bool
Name string `xorm:"unique"`
IsActived bool `xorm:"not null default false"`
Cfg core.Conversion `xorm:"TEXT"`
Created time.Time `xorm:"created"`
Updated time.Time `xorm:"updated"`
}
func (source *LoginSource) TypeString() string {
return LoginTypes[source.Type]
}
func (source *LoginSource) LDAP() *LDAPConfig {
return source.Cfg.(*LDAPConfig)
}
// for xorm callback
func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) {
if colName == "type" {
ty := (*val).(int64)
switch ty {
case LT_LDAP:
source.Cfg = new(LDAPConfig)
}
}
}
func GetAuths() ([]*LoginSource, error) {
var auths = make([]*LoginSource, 0)
err := orm.Find(&auths)
return auths, err
}
func GetLoginSourceById(id int64) (*LoginSource, error) {
source := new(LoginSource)
has, err := orm.Id(id).Get(source)
if err != nil {
return nil, err
}
if !has {
return nil, ErrAuthenticationNotExist
}
return source, nil
}
func AddLDAPSource(name string, cfg *LDAPConfig) error {
_, err := orm.Insert(&LoginSource{Type: LT_LDAP,
Name: name,
@ -54,17 +99,19 @@ func AddLDAPSource(name string, cfg *LDAPConfig) error {
return err
}
func UpdateLDAPSource(id int64, name string, cfg *LDAPConfig) error {
_, err := orm.AllCols().Id(id).Update(&LoginSource{
Id: id,
Type: LT_LDAP,
Name: name,
Cfg: cfg,
})
func UpdateLDAPSource(source *LoginSource) error {
_, err := orm.AllCols().Id(source.Id).Update(source)
return err
}
func DelLoginSource(id int64) error {
_, err := orm.Id(id).Delete(&LoginSource{})
func DelLoginSource(source *LoginSource) error {
cnt, err := orm.Count(&User{LoginSource: source.Id})
if err != nil {
return err
}
if cnt > 0 {
return ErrAuthenticationUserUsed
}
_, err = orm.Id(source.Id).Delete(&LoginSource{})
return err
}