Commit 303659cb authored by ibuler's avatar ibuler

Change app name apps => terrminal

parent 4531157c
...@@ -57,7 +57,7 @@ INSTALLED_APPS = [ ...@@ -57,7 +57,7 @@ INSTALLED_APPS = [
'ops.apps.OpsConfig', 'ops.apps.OpsConfig',
'audits.apps.AuditsConfig', 'audits.apps.AuditsConfig',
'common.apps.CommonConfig', 'common.apps.CommonConfig',
'apps.apps.TerminalConfig', 'terminal.apps.TerminalConfig',
'rest_framework', 'rest_framework',
'rest_framework.authtoken', 'rest_framework.authtoken',
'bootstrapform', 'bootstrapform',
...@@ -270,7 +270,7 @@ REST_FRAMEWORK = { ...@@ -270,7 +270,7 @@ REST_FRAMEWORK = {
'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.TokenAuthentication',
'users.backends.AppSignAuthentication', 'users.backends.TerminalAuthentication',
), ),
} }
# This setting is required to override the Django's main loop, when running in # This setting is required to override the Django's main loop, when running in
......
...@@ -26,7 +26,7 @@ urlpatterns = [ ...@@ -26,7 +26,7 @@ urlpatterns = [
url(r'^assets/', include('assets.urls')), url(r'^assets/', include('assets.urls')),
url(r'^perms/', include('perms.urls')), url(r'^perms/', include('perms.urls')),
url(r'^(api/)?audits/', include('audits.urls')), url(r'^(api/)?audits/', include('audits.urls')),
url(r'^(api/)?apps/', include('apps.urls')), url(r'^(api/)?terminal/', include('terminal.urls')),
] ]
......
...@@ -4447,7 +4447,7 @@ extend(SVGRenderer.prototype, { ...@@ -4447,7 +4447,7 @@ extend(SVGRenderer.prototype, {
* START OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
* * * *
* For applications and websites that don't need IE support, like platform * * For applications and websites that don't need IE support, like platform *
* targeted mobile apps and web apps, this code can be removed. * * targeted mobile terminal and web terminal, this code can be removed. *
* * * *
*****************************************************************************/ *****************************************************************************/
......
...@@ -121,7 +121,7 @@ NgApp.controller('TerminalRecordCtrl', function ($scope, $http) { ...@@ -121,7 +121,7 @@ NgApp.controller('TerminalRecordCtrl', function ($scope, $http) {
timelist = timelist.sort(function(a, b){return a-b}); timelist = timelist.sort(function(a, b){return a-b});
totalTime = totalTime * 1000; totalTime = totalTime * 1000;
document.getElementById("afterScrubberText").innerHTML = buildTimeString(totalTime); document.getElementById("afterScrubberText").innerHTML = buildTimeString(totalTime);
term.open(document.getElementById('apps')); term.open(document.getElementById('terminal'));
timer = setInterval(advance, TICK); timer = setInterval(advance, TICK);
}) })
......
...@@ -588,7 +588,7 @@ Terminal.bindKeys = function(document) { ...@@ -588,7 +588,7 @@ Terminal.bindKeys = function(document) {
}, true); }, true);
// If we click somewhere other than a // If we click somewhere other than a
// apps, unfocus the apps. // terminal, unfocus the terminal.
on(document, 'mousedown', function(ev) { on(document, 'mousedown', function(ev) {
if (!Terminal.focus) return; if (!Terminal.focus) return;
...@@ -742,7 +742,7 @@ Terminal.insertStyle = function(document, bg, fg) { ...@@ -742,7 +742,7 @@ Terminal.insertStyle = function(document, bg, fg) {
// textContent doesn't work well with IE for <style> elements. // textContent doesn't work well with IE for <style> elements.
style.innerHTML = '' style.innerHTML = ''
+ '.apps {\n' + '.terminal {\n'
+ ' float: left;\n' + ' float: left;\n'
+ ' border: ' + bg + ' solid 5px;\n' + ' border: ' + bg + ' solid 5px;\n'
+ ' font-family: "DejaVu Sans Mono", "Liberation Mono", monospace;\n' + ' font-family: "DejaVu Sans Mono", "Liberation Mono", monospace;\n'
...@@ -751,7 +751,7 @@ Terminal.insertStyle = function(document, bg, fg) { ...@@ -751,7 +751,7 @@ Terminal.insertStyle = function(document, bg, fg) {
+ ' background: ' + bg + ';\n' + ' background: ' + bg + ';\n'
+ '}\n' + '}\n'
+ '\n' + '\n'
+ '.apps-cursor {\n' + '.terminal-cursor {\n'
+ ' color: ' + bg + ';\n' + ' color: ' + bg + ';\n'
+ ' background: ' + fg + ';\n' + ' background: ' + fg + ';\n'
+ '}\n'; + '}\n';
...@@ -802,7 +802,7 @@ Terminal.prototype.open = function(parent) { ...@@ -802,7 +802,7 @@ Terminal.prototype.open = function(parent) {
this.isMSIE = !!~this.context.navigator.userAgent.indexOf('MSIE'); this.isMSIE = !!~this.context.navigator.userAgent.indexOf('MSIE');
} }
// Create our main apps element. // Create our main terminal element.
this.element = this.document.createElement('div'); this.element = this.document.createElement('div');
this.element.className = 'terminal'; this.element.className = 'terminal';
this.element.style.outline = 'none'; this.element.style.outline = 'none';
...@@ -811,7 +811,7 @@ Terminal.prototype.open = function(parent) { ...@@ -811,7 +811,7 @@ Terminal.prototype.open = function(parent) {
this.element.style.backgroundColor = this.colors[256]; this.element.style.backgroundColor = this.colors[256];
this.element.style.color = this.colors[257]; this.element.style.color = this.colors[257];
// Create the lines for our apps. // Create the lines for our terminal.
this.children = []; this.children = [];
for (; i < this.rows; i++) { for (; i < this.rows; i++) {
div = this.document.createElement('div'); div = this.document.createElement('div');
...@@ -1020,7 +1020,7 @@ Terminal.prototype.open = function(parent) { ...@@ -1020,7 +1020,7 @@ Terminal.prototype.open = function(parent) {
if (!('useMouse' in this.options) || this.options.useMouse) { if (!('useMouse' in this.options) || this.options.useMouse) {
// Listen for mouse events and translate // Listen for mouse events and translate
// them into apps mouse protocols. // them into terminal mouse protocols.
this.bindMouse(); this.bindMouse();
} }
...@@ -1549,7 +1549,7 @@ Terminal.prototype.refresh = function(start, end) { ...@@ -1549,7 +1549,7 @@ Terminal.prototype.refresh = function(start, end) {
} }
if (data !== this.defAttr) { if (data !== this.defAttr) {
if (data === -1) { if (data === -1) {
out += '<span class="reverse-video apps-cursor">'; out += '<span class="reverse-video terminal-cursor">';
} else { } else {
out += '<span style="'; out += '<span style="';
...@@ -1660,7 +1660,7 @@ Terminal.prototype.refresh = function(start, end) { ...@@ -1660,7 +1660,7 @@ Terminal.prototype.refresh = function(start, end) {
} }
if (this._textarea) { if (this._textarea) {
var cursorElement = this.element.querySelector('.apps-cursor'); var cursorElement = this.element.querySelector('.terminal-cursor');
if(cursorElement){ if(cursorElement){
var cursor_x = cursorElement.offsetLeft; var cursor_x = cursorElement.offsetLeft;
var cursor_y = cursorElement.offsetTop; var cursor_y = cursorElement.offsetTop;
...@@ -2474,7 +2474,7 @@ Terminal.prototype.write = function(data) { ...@@ -2474,7 +2474,7 @@ Terminal.prototype.write = function(data) {
// break; // break;
// CSI > Ps p Set pointer mode. // CSI > Ps p Set pointer mode.
// CSI ! p Soft apps reset (DECSTR). // CSI ! p Soft terminal reset (DECSTR).
// CSI Ps$ p // CSI Ps$ p
// Request ANSI mode (DECRQM). // Request ANSI mode (DECRQM).
// CSI ? Ps$ p // CSI ? Ps$ p
...@@ -3959,7 +3959,7 @@ Terminal.prototype.HPositionRelative = function(params) { ...@@ -3959,7 +3959,7 @@ Terminal.prototype.HPositionRelative = function(params) {
}; };
// CSI Ps c Send Device Attributes (Primary DA). // CSI Ps c Send Device Attributes (Primary DA).
// Ps = 0 or omitted -> request attributes from apps. The // Ps = 0 or omitted -> request attributes from terminal. The
// response depends on the decTerminalID resource setting. // response depends on the decTerminalID resource setting.
// -> CSI ? 1 ; 2 c (``VT100 with Advanced Video Option'') // -> CSI ? 1 ; 2 c (``VT100 with Advanced Video Option'')
// -> CSI ? 1 ; 0 c (``VT101 with No Options'') // -> CSI ? 1 ; 0 c (``VT101 with No Options'')
...@@ -3967,7 +3967,7 @@ Terminal.prototype.HPositionRelative = function(params) { ...@@ -3967,7 +3967,7 @@ Terminal.prototype.HPositionRelative = function(params) {
// -> CSI ? 6 0 ; 1 ; 2 ; 6 ; 8 ; 9 ; 1 5 ; c (``VT220'') // -> CSI ? 6 0 ; 1 ; 2 ; 6 ; 8 ; 9 ; 1 5 ; c (``VT220'')
// The VT100-style response parameters do not mean anything by // The VT100-style response parameters do not mean anything by
// themselves. VT220 parameters do, telling the host what fea- // themselves. VT220 parameters do, telling the host what fea-
// tures the apps supports: // tures the terminal supports:
// Ps = 1 -> 132-columns. // Ps = 1 -> 132-columns.
// Ps = 2 -> Printer. // Ps = 2 -> Printer.
// Ps = 6 -> Selective erase. // Ps = 6 -> Selective erase.
...@@ -3978,12 +3978,12 @@ Terminal.prototype.HPositionRelative = function(params) { ...@@ -3978,12 +3978,12 @@ Terminal.prototype.HPositionRelative = function(params) {
// Ps = 2 9 -> ANSI text locator (i.e., DEC Locator mode). // Ps = 2 9 -> ANSI text locator (i.e., DEC Locator mode).
// CSI > Ps c // CSI > Ps c
// Send Device Attributes (Secondary DA). // Send Device Attributes (Secondary DA).
// Ps = 0 or omitted -> request the apps's identification // Ps = 0 or omitted -> request the terminal's identification
// code. The response depends on the decTerminalID resource set- // code. The response depends on the decTerminalID resource set-
// ting. It should apply only to VT220 and up, but xterm extends // ting. It should apply only to VT220 and up, but xterm extends
// this to VT100. // this to VT100.
// -> CSI > Pp ; Pv ; Pc c // -> CSI > Pp ; Pv ; Pc c
// where Pp denotes the apps type // where Pp denotes the terminal type
// Pp = 0 -> ``VT100''. // Pp = 0 -> ``VT100''.
// Pp = 1 -> ``VT220''. // Pp = 1 -> ``VT220''.
// and Pv is the firmware version (for xterm, this was originally // and Pv is the firmware version (for xterm, this was originally
...@@ -3992,7 +3992,7 @@ Terminal.prototype.HPositionRelative = function(params) { ...@@ -3992,7 +3992,7 @@ Terminal.prototype.HPositionRelative = function(params) {
// always zero. // always zero.
// More information: // More information:
// xterm/charproc.c - line 2012, for more information. // xterm/charproc.c - line 2012, for more information.
// vim responds with ^[[?0c or ^[[?1c after the apps's response (?) // vim responds with ^[[?0c or ^[[?1c after the terminal's response (?)
Terminal.prototype.sendDeviceAttributes = function(params) { Terminal.prototype.sendDeviceAttributes = function(params) {
if (params[0] > 0) return; if (params[0] > 0) return;
...@@ -4217,19 +4217,19 @@ Terminal.prototype.setMode = function(params) { ...@@ -4217,19 +4217,19 @@ Terminal.prototype.setMode = function(params) {
// focusout: ^[[O // focusout: ^[[O
this.sendFocus = true; this.sendFocus = true;
break; break;
case 1005: // utf8 apps mode mouse case 1005: // utf8 terminal mode mouse
this.utfMouse = true; this.utfMouse = true;
// for wide terminals // for wide terminals
// simply encodes large values as utf8 characters // simply encodes large values as utf8 characters
break; break;
case 1006: // sgr apps mode mouse case 1006: // sgr terminal mode mouse
this.sgrMouse = true; this.sgrMouse = true;
// for wide terminals // for wide terminals
// does not add 32 to fields // does not add 32 to fields
// press: ^[[<b;x;yM // press: ^[[<b;x;yM
// release: ^[[<b;x;ym // release: ^[[<b;x;ym
break; break;
case 1015: // urxvt apps mode mouse case 1015: // urxvt terminal mode mouse
this.urxvtMouse = true; this.urxvtMouse = true;
// for wide terminals // for wide terminals
// numbers for fields // numbers for fields
...@@ -4406,13 +4406,13 @@ Terminal.prototype.resetMode = function(params) { ...@@ -4406,13 +4406,13 @@ Terminal.prototype.resetMode = function(params) {
case 1004: // send focusin/focusout events case 1004: // send focusin/focusout events
this.sendFocus = false; this.sendFocus = false;
break; break;
case 1005: // utf8 apps mode mouse case 1005: // utf8 terminal mode mouse
this.utfMouse = false; this.utfMouse = false;
break; break;
case 1006: // sgr apps mode mouse case 1006: // sgr terminal mode mouse
this.sgrMouse = false; this.sgrMouse = false;
break; break;
case 1015: // urxvt apps mode mouse case 1015: // urxvt terminal mode mouse
this.urxvtMouse = false; this.urxvtMouse = false;
break; break;
case 25: // hide cursor case 25: // hide cursor
...@@ -4622,7 +4622,7 @@ Terminal.prototype.setPointerMode = function(params) { ...@@ -4622,7 +4622,7 @@ Terminal.prototype.setPointerMode = function(params) {
; ;
}; };
// CSI ! p Soft apps reset (DECSTR). // CSI ! p Soft terminal reset (DECSTR).
// http://vt100.net/docs/vt220-rm/table4-10.html // http://vt100.net/docs/vt220-rm/table4-10.html
Terminal.prototype.softReset = function(params) { Terminal.prototype.softReset = function(params) {
this.cursorHidden = false; this.cursorHidden = false;
...@@ -4870,7 +4870,7 @@ Terminal.prototype.enableFilterRectangle = function(params) { ...@@ -4870,7 +4870,7 @@ Terminal.prototype.enableFilterRectangle = function(params) {
// CSI Ps x Request Terminal Parameters (DECREQTPARM). // CSI Ps x Request Terminal Parameters (DECREQTPARM).
// if Ps is a "0" (default) or "1", and xterm is emulating VT100, // if Ps is a "0" (default) or "1", and xterm is emulating VT100,
// the control sequence elicits a response of the same form whose // the control sequence elicits a response of the same form whose
// parameters describe the apps: // parameters describe the terminal:
// Ps -> the given Ps incremented by 2. // Ps -> the given Ps incremented by 2.
// Pn = 1 <- no parity. // Pn = 1 <- no parity.
// Pn = 1 <- eight bits. // Pn = 1 <- eight bits.
...@@ -6030,7 +6030,7 @@ Terminal.charsets = {}; ...@@ -6030,7 +6030,7 @@ Terminal.charsets = {};
// DEC Special Character and Line Drawing Set. // DEC Special Character and Line Drawing Set.
// http://vt100.net/docs/vt102-ug/table5-13.html // http://vt100.net/docs/vt102-ug/table5-13.html
// A lot of curses apps use this if they see TERM=xterm. // A lot of curses terminal use this if they see TERM=xterm.
// testing: echo -e '\e(0a\e(B' // testing: echo -e '\e(0a\e(B'
// The xterm output sometimes seems to conflict with the // The xterm output sometimes seems to conflict with the
// reference above. xterm seems in line with the reference // reference above. xterm seems in line with the reference
...@@ -6113,7 +6113,7 @@ function inherits(child, parent) { ...@@ -6113,7 +6113,7 @@ function inherits(child, parent) {
} }
// if bold is broken, we can't // if bold is broken, we can't
// use it in the apps. // use it in the terminal.
function isBoldBroken(document) { function isBoldBroken(document) {
var body = document.getElementsByTagName('body')[0]; var body = document.getElementsByTagName('body')[0];
var terminal = document.createElement('div'); var terminal = document.createElement('div');
......
...@@ -13,7 +13,7 @@ WSSHClient.prototype._generateEndpoint = function (options) { ...@@ -13,7 +13,7 @@ WSSHClient.prototype._generateEndpoint = function (options) {
var protocol = 'ws://'; var protocol = 'ws://';
} }
var endpoint = protocol + document.URL.match(RegExp('//(.*?)/'))[1] + '/ws/apps' + document.URL.match(/(\?.*)/); var endpoint = protocol + document.URL.match(RegExp('//(.*?)/'))[1] + '/ws/terminal' + document.URL.match(/(\?.*)/);
return endpoint; return endpoint;
}; };
WSSHClient.prototype.connect = function (options) { WSSHClient.prototype.connect = function (options) {
...@@ -81,7 +81,7 @@ function openTerminal(options) { ...@@ -81,7 +81,7 @@ function openTerminal(options) {
term.on('data', function (data) { term.on('data', function (data) {
client.send(data) client.send(data)
}); });
$('.apps').detach().appendTo('#term'); $('.terminal').detach().appendTo('#term');
//term.resize(colWidth, rowHeight); //term.resize(colWidth, rowHeight);
term.write('Connecting...'); term.write('Connecting...');
client.connect($.extend(options, { client.connect($.extend(options, {
...@@ -100,13 +100,13 @@ function openTerminal(options) { ...@@ -100,13 +100,13 @@ function openTerminal(options) {
term.write(data); term.write(data);
} }
})); }));
//rowHeight = 0.0 + 1.00 * $('.apps').height() / 24; //rowHeight = 0.0 + 1.00 * $('.terminal').height() / 24;
//colWidth = 0.0 + 1.00 * $('.apps').width() / 80; //colWidth = 0.0 + 1.00 * $('.terminal').width() / 80;
return {'term': term, 'client': client}; return {'term': term, 'client': client};
} }
//function resize() { //function resize() {
// $('.apps').css('width', window.innerWidth - 25); // $('.terminal').css('width', window.innerWidth - 25);
// console.log(window.innerWidth); // console.log(window.innerWidth);
// console.log(window.innerWidth - 10); // console.log(window.innerWidth - 10);
// var rows = Math.floor(window.innerHeight / rowHeight) - 2; // var rows = Math.floor(window.innerHeight / rowHeight) - 2;
...@@ -145,10 +145,10 @@ $(document).ready(function () { ...@@ -145,10 +145,10 @@ $(document).ready(function () {
term_client.client.send({'resize': {'rows': row, 'cols': col}}); term_client.client.send({'resize': {'rows': row, 'cols': col}});
$('#ssh').show(); $('#ssh').show();
}); });
$(".apps").mouseleave(function () { $(".terminal").mouseleave(function () {
$(".termChangBar").slideDown(); $(".termChangBar").slideDown();
}); });
$(".apps").mouseenter(function () { $(".terminal").mouseenter(function () {
$(".termChangBar").slideUp(); $(".termChangBar").slideUp();
}) })
}); });
\ No newline at end of file
...@@ -47,7 +47,7 @@ WSSHClient.prototype._generateEndpoint = function(options) { ...@@ -47,7 +47,7 @@ WSSHClient.prototype._generateEndpoint = function(options) {
var protocol = 'ws://'; var protocol = 'ws://';
} }
var endpoint = protocol + window.location.host + ':8080' + '/apps'; var endpoint = protocol + window.location.host + ':8080' + '/terminal';
return endpoint; return endpoint;
}; };
......
...@@ -35,7 +35,7 @@ ...@@ -35,7 +35,7 @@
</ul> </ul>
</li> </li>
<li id=""> <li id="">
<a href="{% url 'apps:apps-list' %}"> <a href="{% url 'terminal:terminal-list' %}">
<i class="fa fa-desktop"></i><span class="nav-label">{% trans 'Terminal' %}</span><span class="label label-info pull-right"></span> <i class="fa fa-desktop"></i><span class="nav-label">{% trans 'Terminal' %}</span><span class="label label-info pull-right"></span>
</a> </a>
</li> </li>
......
...@@ -3,5 +3,5 @@ from __future__ import unicode_literals ...@@ -3,5 +3,5 @@ from __future__ import unicode_literals
from django.apps import AppConfig from django.apps import AppConfig
class AppsConfig(AppConfig): class TerminalConfig(AppConfig):
name = 'apps' name = 'terminal'
...@@ -19,11 +19,27 @@ class Terminal(models.Model): ...@@ -19,11 +19,27 @@ class Terminal(models.Model):
type = models.CharField(choices=TYPE_CHOICES, max_length=2, verbose_name=_('Terminal type')) type = models.CharField(choices=TYPE_CHOICES, max_length=2, verbose_name=_('Terminal type'))
url = models.CharField(max_length=100, verbose_name=_('URL to login')) url = models.CharField(max_length=100, verbose_name=_('URL to login'))
mail_to = models.ManyToManyField(User, verbose_name=_('Mail to')) mail_to = models.ManyToManyField(User, verbose_name=_('Mail to'))
is_accepted = models.BooleanField(default=False, verbose_name=_('Is accepted'))
date_created = models.DateTimeField(auto_now_add=True) date_created = models.DateTimeField(auto_now_add=True)
comment = models.TextField(verbose_name=_('Comment')) comment = models.TextField(verbose_name=_('Comment'))
def is_valid(self):
return self.is_active and self.is_accepted
@property
def is_superuser(self):
return False
@property
def is_terminal(self):
return True
@property
def is_authenticated(self):
return False
class Meta: class Meta:
db_table = 'apps' db_table = 'terminal'
ordering = ['name'] ordering = ['name']
......
...@@ -68,7 +68,7 @@ $(document).ready(function(){ ...@@ -68,7 +68,7 @@ $(document).ready(function(){
{# $(td).html(update_btn + del_btn)#} {# $(td).html(update_btn + del_btn)#}
{# }}],#} {# }}],#}
{# ],#} {# ],#}
ajax_url: '{% url "apps:apps-list-create-api" %}', ajax_url: '{% url "terminal:terminal-list-create-api" %}',
columns: [{data: function(){return ""}}, {data: "name" }, {data: "ip" }, {data: "get_type_display" }, {data: "url" }, columns: [{data: function(){return ""}}, {data: "name" }, {data: "ip" }, {data: "get_type_display" }, {data: "url" },
{data: "is_active" }, {data: "ip"}], {data: "is_active" }, {data: "ip"}],
op_html: $('#actions').html() op_html: $('#actions').html()
......
...@@ -7,12 +7,12 @@ from django.conf.urls import url ...@@ -7,12 +7,12 @@ from django.conf.urls import url
import views import views
import api import api
app_name = 'apps' app_name = 'terminal'
urlpatterns = [ urlpatterns = [
url(r'^apps$', views.TerminalListView.as_view(), name='apps-list'), url(r'^terminal$', views.TerminalListView.as_view(), name='terminal-list'),
] ]
urlpatterns += [ urlpatterns += [
url(r'^v1/apps/$', api.TerminalApi.as_view(), name='apps-list-create-api'), url(r'^v1/terminal/$', api.TerminalApi.as_view(), name='terminal-list-create-api'),
] ]
...@@ -9,7 +9,7 @@ from .models import Terminal ...@@ -9,7 +9,7 @@ from .models import Terminal
class TerminalListView(ListView): class TerminalListView(ListView):
model = Terminal model = Terminal
template_name = 'apps/terminal_list.html' template_name = 'terminal/terminal_list.html'
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(TerminalListView, self).get_context_data(**kwargs) context = super(TerminalListView, self).get_context_data(**kwargs)
......
...@@ -12,7 +12,7 @@ from common.utils import get_logger ...@@ -12,7 +12,7 @@ from common.utils import get_logger
from .models import User, UserGroup from .models import User, UserGroup
from .serializers import UserDetailSerializer, UserAndGroupSerializer, \ from .serializers import UserDetailSerializer, UserAndGroupSerializer, \
GroupDetailSerializer, UserPKUpdateSerializer, UserBulkUpdateSerializer, GroupBulkUpdateSerializer GroupDetailSerializer, UserPKUpdateSerializer, UserBulkUpdateSerializer, GroupBulkUpdateSerializer
from .backends import IsSuperUser, IsAppUser, IsValidUser, IsSuperUserOrAppUser from .backends import IsSuperUser, IsTerminalUser, IsValidUser, IsSuperUserOrTerminalUser
logger = get_logger(__name__) logger = get_logger(__name__)
...@@ -87,7 +87,7 @@ class GroupDetailApi(generics.RetrieveUpdateDestroyAPIView): ...@@ -87,7 +87,7 @@ class GroupDetailApi(generics.RetrieveUpdateDestroyAPIView):
class UserListUpdateApi(BulkDeleteApiMixin, ListBulkCreateUpdateDestroyAPIView): class UserListUpdateApi(BulkDeleteApiMixin, ListBulkCreateUpdateDestroyAPIView):
queryset = User.objects.all() queryset = User.objects.all()
serializer_class = UserBulkUpdateSerializer serializer_class = UserBulkUpdateSerializer
permission_classes = (IsSuperUserOrAppUser,) permission_classes = (IsSuperUserOrTerminalUser,)
# def get(self, request, *args, **kwargs): # def get(self, request, *args, **kwargs):
# return super(UserListUpdateApi, self).get(request, *args, **kwargs) # return super(UserListUpdateApi, self).get(request, *args, **kwargs)
......
...@@ -6,12 +6,12 @@ from rest_framework.compat import is_authenticated ...@@ -6,12 +6,12 @@ from rest_framework.compat import is_authenticated
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from common.utils import unsign, get_object_or_none from common.utils import unsign, get_object_or_none
from .models import User from .hands import Terminal
class AppSignAuthentication(authentication.BaseAuthentication): class TerminalAuthentication(authentication.BaseAuthentication):
keyword = 'Sign' keyword = 'Sign'
model = User model = Terminal
def authenticate(self, request): def authenticate(self, request):
auth = authentication.get_authorization_header(request).split() auth = authentication.get_authorization_header(request).split()
...@@ -34,15 +34,16 @@ class AppSignAuthentication(authentication.BaseAuthentication): ...@@ -34,15 +34,16 @@ class AppSignAuthentication(authentication.BaseAuthentication):
return self.authenticate_credentials(sign) return self.authenticate_credentials(sign)
def authenticate_credentials(self, sign): def authenticate_credentials(self, sign):
app = unsign(sign, max_age=300) name = unsign(sign, max_age=300)
if app: if name:
user = get_object_or_none(self.model, username=app, role='App') terminal = get_object_or_none(self.model, name=name)
else: else:
raise exceptions.AuthenticationFailed(_('Invalid sign.')) raise exceptions.AuthenticationFailed(_('Invalid sign.'))
if not user.is_active: if not terminal.is_active:
raise exceptions.AuthenticationFailed(_('User inactive or deleted.')) raise exceptions.AuthenticationFailed(_('Terminal inactive or deleted.'))
return user, None terminal.is_authenticated = True
return terminal, None
class IsValidUser(permissions.IsAuthenticated, permissions.BasePermission): class IsValidUser(permissions.IsAuthenticated, permissions.BasePermission):
...@@ -53,12 +54,12 @@ class IsValidUser(permissions.IsAuthenticated, permissions.BasePermission): ...@@ -53,12 +54,12 @@ class IsValidUser(permissions.IsAuthenticated, permissions.BasePermission):
and request.user.is_valid and request.user.is_valid
class IsAppUser(IsValidUser, permissions.BasePermission): class IsTerminalUser(IsValidUser, permissions.BasePermission):
"""Allows access only to app user """ """Allows access only to app user """
def has_permission(self, request, view): def has_permission(self, request, view):
return super(IsAppUser, self).has_permission(request, view) \ return super(IsTerminalUser, self).has_permission(request, view) \
and request.user.is_app_user and isinstance(request.user, Terminal)
class IsSuperUser(IsValidUser, permissions.BasePermission): class IsSuperUser(IsValidUser, permissions.BasePermission):
...@@ -69,12 +70,12 @@ class IsSuperUser(IsValidUser, permissions.BasePermission): ...@@ -69,12 +70,12 @@ class IsSuperUser(IsValidUser, permissions.BasePermission):
and request.user.is_superuser and request.user.is_superuser
class IsSuperUserOrAppUser(IsValidUser, permissions.BasePermission): class IsSuperUserOrTerminalUser(IsValidUser, permissions.BasePermission):
"""Allows access between superuser and app user""" """Allows access between superuser and app user"""
def has_permission(self, request, view): def has_permission(self, request, view):
return super(IsSuperUserOrAppUser, self).has_permission(request, view) \ return super(IsSuperUserOrTerminalUser, self).has_permission(request, view) \
and (request.user.is_superuser or request.user.is_app_user) and (request.user.is_superuser or request.user.is_terminal)
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -12,3 +12,4 @@ ...@@ -12,3 +12,4 @@
from perms.models import AssetPermission from perms.models import AssetPermission
from perms.utils import get_user_granted_assets, get_user_granted_asset_groups from perms.utils import get_user_granted_assets, get_user_granted_asset_groups
from terminal.models import Terminal
\ No newline at end of file
...@@ -141,6 +141,10 @@ class User(AbstractUser): ...@@ -141,6 +141,10 @@ class User(AbstractUser):
else: else:
return False return False
@property
def is_terminal(self):
return False
@is_superuser.setter @is_superuser.setter
def is_superuser(self, value): def is_superuser(self, value):
if value is True: if value is True:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment