or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mdauthorization.mdcore-setup.mddatabase.mdindex.mdpassword-management.mdregistration.mdtwo-factor.mdunified-signin.mdutilities.mdwebauthn.md

core-setup.mddocs/

0

# Core Setup & Configuration

1

2

Essential classes and functions for initializing Flask-Security in your application, including the main Security extension class, user/role mixins, and configuration management.

3

4

## Capabilities

5

6

### Security Extension Class

7

8

The main Flask-Security extension class that initializes and configures the security framework for your Flask application.

9

10

```python { .api }

11

class Security:

12

"""

13

Main Flask-Security extension class.

14

15

Parameters:

16

- app: Flask application instance (optional)

17

- datastore: User datastore instance

18

- register_blueprint: Whether to register security blueprint (default: True)

19

- login_form: Custom login form class

20

- confirm_register_form: Custom registration confirmation form class

21

- register_form: Custom registration form class

22

- forgot_password_form: Custom forgot password form class

23

- reset_password_form: Custom reset password form class

24

- change_password_form: Custom change password form class

25

- send_confirmation_form: Custom send confirmation form class

26

- passwordless_login_form: Custom passwordless login form class

27

"""

28

def __init__(self, app=None, datastore=None, **kwargs): ...

29

30

def init_app(self, app, datastore, register_blueprint=True, **kwargs): ...

31

```

32

33

### User Model Mixin

34

35

Base mixin providing standard methods and properties required for Flask-Security user models.

36

37

```python { .api }

38

class UserMixin:

39

"""

40

Mixin for user models providing authentication interface.

41

42

Required attributes (implement in your User model):

43

- id: User identifier

44

- email: User email address

45

- password: Hashed password

46

- active: Boolean indicating if user is active

47

"""

48

49

def is_authenticated(self) -> bool:

50

"""Return True if user is authenticated."""

51

52

def is_active(self) -> bool:

53

"""Return True if user account is active."""

54

55

def is_anonymous(self) -> bool:

56

"""Return False for real users (always False for UserMixin)."""

57

58

def get_id(self) -> str:

59

"""Return unique identifier for user as unicode string."""

60

61

def has_role(self, role) -> bool:

62

"""Return True if user has the specified role."""

63

64

def get_security_payload(self) -> dict:

65

"""Return user data for token payload."""

66

67

@property

68

def roles(self):

69

"""Return list of roles assigned to user."""

70

71

def get_auth_token(self) -> str:

72

"""Generate authentication token for user."""

73

```

74

75

### Role Model Mixin

76

77

Base mixin providing standard methods and properties for Flask-Security role models.

78

79

```python { .api }

80

class RoleMixin:

81

"""

82

Mixin for role models providing role comparison interface.

83

84

Required attributes (implement in your Role model):

85

- name: Role name

86

- description: Role description (optional)

87

"""

88

89

def __eq__(self, other) -> bool:

90

"""Compare roles for equality."""

91

92

def __ne__(self, other) -> bool:

93

"""Compare roles for inequality."""

94

95

def __hash__(self) -> int:

96

"""Return hash of role for set operations."""

97

```

98

99

### WebAuthn Model Mixin

100

101

Mixin providing WebAuthn credential management for user models when WebAuthn is enabled.

102

103

```python { .api }

104

class WebAuthnMixin:

105

"""

106

Mixin for user models providing WebAuthn credential interface.

107

"""

108

109

@property

110

def webauthn_credentials(self):

111

"""Return list of WebAuthn credentials for user."""

112

113

def get_webauthn_credential_by_id(self, credential_id):

114

"""Get WebAuthn credential by ID."""

115

116

def get_webauthn_credential_options(self) -> dict:

117

"""Get options for WebAuthn credential creation."""

118

```

119

120

### Current User Access

121

122

Proxy object providing access to the currently authenticated user in the request context.

123

124

```python { .api }

125

def current_user():

126

"""

127

Proxy to the current user object for the request.

128

129

Returns:

130

- User object if authenticated

131

- AnonymousUser object if not authenticated

132

"""

133

```

134

135

### Anonymous User

136

137

Default anonymous user implementation for unauthenticated requests.

138

139

```python { .api }

140

class AnonymousUser:

141

"""

142

Anonymous user object for unauthenticated requests.

143

"""

144

145

def is_authenticated(self) -> bool:

146

"""Return False for anonymous users."""

147

148

def is_active(self) -> bool:

149

"""Return False for anonymous users."""

150

151

def is_anonymous(self) -> bool:

152

"""Return True for anonymous users."""

153

154

def get_id(self) -> None:

155

"""Return None for anonymous users."""

156

157

def has_role(self, role) -> bool:

158

"""Return False for anonymous users."""

159

```

160

161

### Form Configuration

162

163

Dataclass for storing form configuration information used internally by Flask-Security.

164

165

```python { .api }

166

class FormInfo:

167

"""

168

Dataclass containing form configuration information.

169

170

Attributes:

171

- form_class: Form class to instantiate

172

- form_args: Arguments to pass to form constructor

173

- form_kwargs: Keyword arguments to pass to form constructor

174

"""

175

form_class: type

176

form_args: tuple = ()

177

form_kwargs: dict = None

178

```

179

180

## Usage Examples

181

182

### Basic Setup with SQLAlchemy

183

184

```python

185

from flask import Flask

186

from flask_sqlalchemy import SQLAlchemy

187

from flask_security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin

188

189

app = Flask(__name__)

190

app.config['SECRET_KEY'] = 'super-secret'

191

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'

192

193

db = SQLAlchemy(app)

194

195

# Define User and Role models

196

roles_users = db.Table('roles_users',

197

db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),

198

db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))

199

)

200

201

class Role(db.Model, RoleMixin):

202

id = db.Column(db.Integer(), primary_key=True)

203

name = db.Column(db.String(80), unique=True)

204

description = db.Column(db.String(255))

205

206

class User(db.Model, UserMixin):

207

id = db.Column(db.Integer, primary_key=True)

208

email = db.Column(db.String(255), unique=True)

209

password = db.Column(db.String(255))

210

active = db.Column(db.Boolean(), default=True)

211

roles = db.relationship('Role', secondary=roles_users,

212

backref=db.backref('users', lazy='dynamic'))

213

214

# Initialize Flask-Security

215

user_datastore = SQLAlchemyUserDatastore(db, User, Role)

216

security = Security(app, user_datastore)

217

```

218

219

### Setup with Custom Forms

220

221

```python

222

from flask_security import Security, RegisterForm

223

from wtforms import StringField

224

from wtforms.validators import DataRequired

225

226

class ExtendedRegisterForm(RegisterForm):

227

first_name = StringField('First Name', [DataRequired()])

228

last_name = StringField('Last Name', [DataRequired()])

229

230

security = Security(app, user_datastore, register_form=ExtendedRegisterForm)

231

```

232

233

### Configuration Options

234

235

```python

236

app.config['SECURITY_REGISTERABLE'] = True

237

app.config['SECURITY_RECOVERABLE'] = True

238

app.config['SECURITY_CONFIRMABLE'] = True

239

app.config['SECURITY_PASSWORD_SALT'] = 'your-salt-here'

240

app.config['SECURITY_LOGIN_URL'] = '/auth/login'

241

app.config['SECURITY_LOGOUT_URL'] = '/auth/logout'

242

```