def autenticar(request, matricula, rowguid):
    aluno = PreInscricao.objects.get(matricula=matricula)

    try:
        user = aluno.user_info.user
        user = authenticate(username=matricula, password=rowguid)
        if not user:
            user = aluno.user_info.user
            user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, user)
        request.session['site_interno'] = True

        return HttpResponseRedirect(reverse('portal.accounts.views.user_info', args=[request.user.id,]))
    except:
        aluno_role = UserDisciplineRole.objects.student_role()
        User.objects.create_user(aluno.email, aluno.email, rowguid).save()
        user = authenticate(username=aluno.email, password=rowguid)
        user_info = UserInfo(name=aluno.nome,city=aluno.cidade,province=aluno.estado,email=aluno.email, user=user, birth_date=aluno.data_nasc)
        user_info.save()
        aluno.user_info = user_info
        aluno.save()
        login(request, user)

        institutions = set()
        courses      = set()

        for id_disc in aluno.disciplinas:
            try:
                disciplina = DisciplineMetadata.objects.get(cod_turma=id_disc, periodo=PERIODO_ATUAL).discipline

                institutions.add(disciplina.course.institution.id)
                courses.add(disciplina.course.id)

                #Associando a disciplina ao aluno
                queryset = RelUserDiscipline.objects.filter(role=aluno_role, user=user_info, discipline=disciplina, period=PERIODO_ATUAL)
                if not queryset.exists():
                    RelUserDiscipline(user=user_info, discipline=disciplina, role=aluno_role, period=PERIODO_ATUAL).save()

                #Associando o aluno ao curso
                queryset = RelUserCourse.objects.filter(role=UserCourseRole.objects.student_role(), user=user_info, course=disciplina.course, period=PERIODO_ATUAL)
                if not queryset.exists():
                    RelUserCourse(role=UserCourseRole.objects.student_role(), user=user_info, course=disciplina.course, period=PERIODO_ATUAL).save()

                #Associando o aluno à instituição de ensino
                queryset = RelUserInstitution.objects.filter(role=UserInstitutionRole.objects.student_role(), user=user_info, institution=disciplina.course.institution, period=PERIODO_ATUAL)
                if not queryset.exists():
                    RelUserInstitution(role=UserInstitutionRole.objects.student_role(), user=user_info, institution=disciplina.course.institution, period=PERIODO_ATUAL).save()
            except Exception, e:
                logging.exception(e)
                logging.error("[confirma_adicionar_aluno] - Nao foi possivel localizar a disciplina %s" % id_disc)

        #Para cada uma das instituicoes afetadas
        for inst in institutions:
            rebuild_caches_institution(inst) #Reconstroi a sua cache
        #Para cada um dos cursos afetados
        for course in courses:
            rebuild_caches_course(course)

        request.session['site_interno'] = True
        return HttpResponseRedirect(reverse('portal.accounts.views.user_info', args=[request.user.id,]))
def confirma_adicionar_professor(request):
    nome        = request.POST['nome']
    email       = request.POST['email']
    data_nasc   = request.POST['data_nasc']
    data_nasc   = data_nasc.split('/')
    data_nasc   = datetime.date(int(data_nasc[2]), int(data_nasc[1]), int(data_nasc[0]))
    senha       = request.POST['senha']
    disciplinas = request.POST['disciplinas'] != '' and request.POST['disciplinas'].split(',') or []
    instituicao = Institution.objects.get(slug=request.POST['instituicao'])

    if User.objects.filter(username=email).exists():
        User.objects.filter(username=email).delete()

    User.objects.create_user(email, email, senha).save()
    user = authenticate(username=email, password=senha)
    user_info = UserInfo(name=nome, email=email, is_teacher=True, birth_date=data_nasc, user=user)
    user_info.save()

    #Associando o professor à instituição de ensino
    queryset = RelUserInstitution.objects.filter(role=UserInstitutionRole.objects.teacher_role(), user=user_info, institution=instituicao)
    if not queryset.exists():
        RelUserInstitution(role=UserInstitutionRole.objects.teacher_role(), user=user_info, institution=instituicao).save()
    rebuild_caches_institution(instituicao.id)

    login(request, user)
    institutions = set()
    courses      = set()

    for d in disciplinas:
        discipline = Discipline.objects.get(pk=d)

        institutions.add(discipline.course.institution.id)
        courses.add(discipline.course.id)

        #Associando a disciplina ao professor
        queryset = RelUserDiscipline.objects.filter(user=user_info, discipline=discipline, role=UserDisciplineRole.objects.teacher_role())
        if not queryset.exists():
            RelUserDiscipline(user=user_info, discipline=discipline, role=UserDisciplineRole.objects.teacher_role()).save()

        #Associando o professor ao curso
        queryset = RelUserCourse.objects.filter(role=UserCourseRole.objects.teacher_role(), user=user_info, course=discipline.course)
        if not queryset.exists():
            RelUserCourse(role=UserCourseRole.objects.teacher_role(), user=user_info, course=discipline.course).save()

        #Associando o professor à instituição de ensino
        queryset = RelUserInstitution.objects.filter(role=UserInstitutionRole.objects.teacher_role(), user=user_info, institution=discipline.course.institution)
        if not queryset.exists():
            RelUserInstitution(role=UserInstitutionRole.objects.teacher_role(), user=user_info, institution=discipline.course.institution).save()

    #Para cada uma das instituicoes afetadas
    for inst in institutions:
        rebuild_caches_institution(inst) #Reconstroi a sua cache
    #Para cada um dos cursos afetados
    for course in courses:
        rebuild_caches_course(course)

    return HttpResponseRedirect(reverse('portal.views.index'))
def confirma_adicionar_aluno(request):
    logging.info('confirma_adicionar_aluno')

    matricula   = request.POST['matricula']
    cpf         = re.sub(r'[\.-]', '', request.POST['cpf'])
    nome        = request.POST['nome']
    email       = request.POST['email']
    queryset    = PreInscricao.objects.filter(matricula=matricula, cpf=cpf)
    senha       = request.POST['senha']
    aluno_role  = UserDisciplineRole.objects.student_role()
    dados_aluno = queryset[0]

    data_nasc = request.POST['data_nasc']
    data_nasc = data_nasc.split('/')
    data_nasc = datetime.date(int(data_nasc[2]), int(data_nasc[1]), int(data_nasc[0]))

    if User.objects.filter(username=email).exists():
        User.objects.filter(username=email).delete()
    User.objects.create_user(email, email, senha).save()
    user = authenticate(username=email, password=senha)

    if UserInfo.objects.filter(email=email).exists():
        #Caso ja exista um usuario, exclui ele do banco
        for u in UserInfo.objects.filter(email=email):
            for r in RelUserInstitution.objects.filter(user__id=u.id):
                r.delete()
            for r in RelUserCourse.objects.filter(user__id=u.id):
                r.delete()
            for r in RelUserDiscipline.objects.filter(user__id=u.id):
                r.delete()
            u.delete()

    user_info = UserInfo(name=nome,city=dados_aluno.cidade,province=dados_aluno.estado,email=email, user=user, birth_date=data_nasc)
    user_info.save()

    dados_aluno.data_nasc = data_nasc
    dados_aluno.nome      = nome
    dados_aluno.email     = email
    dados_aluno.user_info = user_info
    dados_aluno.save()

    login(request, user)
    institutions = set()
    courses      = set()

    for id_disc in dados_aluno.disciplinas:
        try:
            disciplina = DisciplineMetadata.objects.get(cod_turma=id_disc, periodo=PERIODO_ATUAL).discipline

            institutions.add(disciplina.course.institution.id)
            courses.add(disciplina.course.id)

            #Associando a disciplina ao aluno
            queryset = RelUserDiscipline.objects.filter(role=aluno_role, user=user_info, discipline=disciplina, period=PERIODO_ATUAL)
            if not queryset.exists():
                RelUserDiscipline(user=user_info, discipline=disciplina, role=aluno_role, period=PERIODO_ATUAL).save()

            #Associando o aluno ao curso
            queryset = RelUserCourse.objects.filter(role=UserCourseRole.objects.student_role(), user=user_info, course=disciplina.course, period=PERIODO_ATUAL)
            if not queryset.exists():
                RelUserCourse(role=UserCourseRole.objects.student_role(), user=user_info, course=disciplina.course, period=PERIODO_ATUAL).save()

            #Associando o aluno à instituição de ensino
            queryset = RelUserInstitution.objects.filter(role=UserInstitutionRole.objects.student_role(), user=user_info, institution=disciplina.course.institution, period=PERIODO_ATUAL)
            if not queryset.exists():
                RelUserInstitution(role=UserInstitutionRole.objects.student_role(), user=user_info, institution=disciplina.course.institution, period=PERIODO_ATUAL).save()
        except Exception, e:
            logging.exception(e)            
            logging.error("[confirma_adicionar_aluno] - Nao foi possivel localizar a disciplina %s" % id_disc)