Add api authentication

pull/530/head
ibuler 2016-08-25 19:29:59 +08:00
parent 641e998504
commit bb76f6c652
10 changed files with 157 additions and 17 deletions

View File

@ -172,9 +172,13 @@ FIXTURE_DIRS = [os.path.join(BASE_DIR, 'fixtures'), ]
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
),
# 'DEFAULT_AUTHENTICATION_CLASSES': (
# 'rest_framework.authentication.BasicAuthentication',
# 'rest_framework.authentication.SessionAuthentication',
# ),
}
# This setting is required to override the Django's main loop, when running in
# development mode, such as ./manage runserver

BIN
apps/static/img/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

View File

@ -17,4 +17,36 @@
$("#"+s1).addClass('active');
$('#'+s1+' .'+s2).addClass('active');
}
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
console.log(csrftoken)
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
</script>

View File

@ -7,7 +7,7 @@
<a data-toggle="dropdown" class="dropdown-toggle" href="#">
<span class="clear">
<span class="block m-t-xs">
<strong class="font-bold"> Admin <span style="color: #8095a8"></span></strong>
<strong class="font-bold"> {{ request.user.name }}<span style="color: #8095a8"></span></strong>
</span>
<span class="text-muted text-xs block">
{{ role | default:'普通用户' }}<b class="caret"></b>

View File

@ -6,6 +6,19 @@ from django import forms
from .models import User, UserGroup
# class UserLoginForm(ModelForm):
# class Meta:
# model = User
# fields = [
# "email", "password"
# ]
class UserLoginForm(forms.Form):
username = forms.CharField(label='用户名', max_length=100)
password = forms.CharField(label='密码', widget=forms.PasswordInput, max_length=100)
class UserAddForm(ModelForm):
class Meta:
model = User

View File

@ -0,0 +1,48 @@
{% load static %}
{% load bootstrap %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> JumpServer </title>
<link rel="shortcut icon" href="{% static "img/facio.ico" %}" type="image/x-icon">
{% include '_head_css_js.html' %}
<link href="{% static "css/style.css" %}" rel="stylesheet">
<script src="{% static "js/base.js" %}"></script>
</head>
<body class="gray-bg">
<div class="middle-box text-center loginscreen animated fadeInDown">
<div>
<div>
<h1 class="logo-name"><img src="{% static "/img/logo.png" %}"></h1>
</div>
{% if error %}
<div class="alert alert-danger text-center">{{ error }}</div>
{% endif %}
<h2>Welcome to Jumpserver</h2>
<form class="m-t" role="form" method="post" action="">
{% csrf_token %}
<div class="form-group">
<input id="{{ form.username.id_for_label }}" name="{{ form.username.html_name }}" type="text" value="{{ user.username }}" class="form-control" placeholder="Username">
</div>
<div class="form-group">
<input id="{{ form.password.id_for_label }}" name="{{ form.password.html_name }}" type="password" value="{{ user.password }}" class="form-control" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary block full-width m-b">Login</button>
<a href=""><small>Forgot password? </small></a>
</form>
<p class="m-t"> <small><b>Copyright</b> Jumpserver.org Organization © 2014-2015</small> </p>
</div>
</div>
{% include '_foot_js.html' %}
</body>
</html>

View File

@ -62,8 +62,7 @@
<tbody>
<tr>
<td colspan="2">
<img src="{{ user | user_avatar_url }}" class="img-circle" width="64"
height="64">
<img src="{{ user | user_avatar_url }}" class="img-circle" width="64" height="64">
</td>
</tr>
<tr>
@ -134,12 +133,8 @@
<td><span style="float: right">
<div class="switch">
<div class="onoffswitch">
{% if user.is_active %}
<input type="checkbox" checked class="onoffswitch-checkbox" id="example1">
{% else %}
<input type="checkbox" class="onoffswitch-checkbox" id="example1">
{% endif %}
<label class="onoffswitch-label" for="example1">
<input type="checkbox" {% if user.is_active %} checked {% endif %} class="onoffswitch-checkbox" id="is_active" onchange="switch_user_status(this)">
<label class="onoffswitch-label" for="is_active">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
@ -232,6 +227,20 @@
{% endblock %}
{% block custom_foot_js %}
<script>
function switch_user_status(obj) {
var status = $(obj).prop('checked');
$.ajax({
{# url: "{% url 'users:user-detail-api' pk=user.id %}",#}
url: "{% url 'users:login' %}",
type: "POST",
data: {
'username': "{{ user.username }}",
'email': "{{ user.email }}",
'is_active': status
}
})
}
$(document).ready(function () {
$('.select2').select2();
})

View File

@ -3,7 +3,7 @@
<div class="form-group">
<label for="{{ form.username.id_for_label }}" class="col-sm-2 control-label">用户名</label>
<div class="col-sm-9 controls" >
<input id="{{ form.username.id_for_label }}" name="username" type="text" value="{{ user.username }}" readonly class="form-control">
<input id="{{ form.username.id_for_label }}" name="{{ form.username.html_name }}" type="text" value="{{ user.username }}" readonly class="form-control">
</div>
</div>
{% endblock %}

View File

@ -1,12 +1,13 @@
from django.conf.urls import url
from .views import UserListView, UserAddView, UserUpdateView, UserDeleteView, UserDetailView
from .views import UserListView, UserAddView, UserUpdateView, UserDeleteView, UserDetailView, UserLoginView
from .views import UserGroupListView, UserGroupAddView, UserGroupUpdateView, UserGroupDeleteView, UserGroupDetailView
import api
app_name = 'users'
urlpatterns = [
url(r'^login/$', UserLoginView.as_view(), name='login'),
url(r'^users/$', UserListView.as_view(), name='user-list'),
url(r'^users/(?P<pk>[0-9]+)/$', UserDetailView.as_view(), name='user-detail'),
url(r'^users/add/$', UserAddView.as_view(), name='user-add'),

View File

@ -2,17 +2,50 @@
from __future__ import unicode_literals
from django.shortcuts import get_object_or_404, reverse
from django.shortcuts import get_object_or_404, reverse, render
from django.http import HttpResponseRedirect
from django.urls import reverse_lazy
from django.db.models import Q
from django.views.generic.base import TemplateResponseMixin
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, DeleteView, UpdateView
from django.views.generic.edit import CreateView, DeleteView, UpdateView, ProcessFormView, FormView
from django.views.generic.detail import DetailView
from django.contrib.messages.views import SuccessMessageMixin
from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from .models import User, UserGroup
from .forms import UserAddForm, UserUpdateForm, UserGroupForm
from .forms import UserAddForm, UserUpdateForm, UserGroupForm, UserLoginForm
class UserLoginView(FormView):
template_name = 'users/login.html'
form_class = UserLoginForm
success_url = reverse_lazy('users:user-list')
def get(self, request, *args, **kwargs):
if self.request.user.is_staff:
return HttpResponseRedirect(reverse('users:user-list'))
return super(UserLoginView, self).get(request, *args, **kwargs)
# def post(self, request, *args, **kwargs):
# print(self.request.user)
# return HttpResponseRedirect('/')
def form_valid(self, form):
username = form.cleaned_data.get('username', '')
password = form.cleaned_data.get('password', '')
user = authenticate(username=username, password=password)
if user is not None and user.is_staff:
login(self.request, user)
return HttpResponseRedirect(self.success_url)
return render(self.request, self.template_name, context={'form': form, 'error': '密码错误'})
def form_invalid(self, form):
print(form.errors)
return super(UserLoginView, self).form_invalid(form)
class UserListView(ListView):